1

I have a string that contains a few numbers (usually a date) and separators. The separators can either be "," or "." - or example 01.05,2000.5000

....now I need to separate those numbers and put into an array but I'm not sure how to do that (the separating part). Also, I need to check that the string is valid - it cannot be 01.,05.

I'm not asking for anyone to solve the thing for me (but if someone wants I appreciated it), just point me in the right direction :)

3
  • 1
    String#split(...) allows for regular expressions to be used as the delimiter. I'd experiment with that. All you need is something very simple. Commented May 18, 2013 at 1:22
  • Is your string contains "," and '.' both in a single string ? Commented May 18, 2013 at 1:30
  • @JDeveloper I would say yes since his example has both. Commented May 18, 2013 at 1:32

7 Answers 7

1

This is a way of doing it with StringTokenizer class, just iterate the tokens and if the obtained token is empty then you have a invalid String, also, convert the tokens to integers by the parseInt method to check if they are valid integer numbers:

import java.util.*;
public class t {
    public static void main(String... args)  { 
        String line = "01.05,2000.5000";
        StringTokenizer strTok = new StringTokenizer(line, ",.");
        List<Integer> values = new ArrayList<Integer>();
        while (strTok.hasMoreTokens()) {
            String s = strTok.nextToken();
            if (s.length() == 0) { 
                // Found a repeated separator, String is not valid, do something about it
            } 
            try { 
                int value = Integer.parseInt(s, 10);
                values.add(value);
            } catch(NumberFormatException e) { 
                // Number not valid, do something about it or continue the parsing 
            }
        }

        // At the end, get an array from the ArrayList
        Integer[] arrayOfValues = values.toArray(new Integer[values.size()]);

        for (Integer i : arrayOfValues) {
            System.out.println(i);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Iterate through an String#split(regex) generated array and check each value to make sure your source String is "valid".

In:

String src = "01.05,2000.5000";
String[] numbers = src.split("[.,]");

numbers here will be an array of Strings, like {"01", "05", "2000", "5000"}. Each value is a number.

Now iterate over numbers. If you find a index that is not a number (it's a number when numbers[i].matches("\\d+") is true), then your src is invalid.

Comments

1

If possible, I would use guava String splitter for that. It is much more reliable, predictable and flexible than String#split. You can tell it exactly what to expect, what to omit, and so on.

For an example usage, and a small rant on how stupid javas split sometimes behaves, have a look here: http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter

Comments

1

Use regex to group and match the input

    String s = "01.05,2000.5000";       
    Pattern pattern = Pattern.compile("(\\d{2})[.,](\\d{2})[.,](\\d{4})[.,](\\d{4})");      
    Matcher m = pattern.matcher(s);

    if(m.matches()) {
        String[] matches = { m.group(1),m.group(2), m.group(3),m.group(4) };
        for(String match : matches) {
            System.out.println(match);
        }
    } else {
        System.err.println("Mismatch");
    }

Comments

1

Try this:

String str = "01.05,2000.5000";
str = str.replace(".",",");
int number = StringUtils.countMatches(str, ",");
String[] arrayStr = new String[number+1];
arrayStr = str.split(",");

StringUtils is from Apache Commons >> http://commons.apache.org/proper/commons-lang/

Comments

1

To validate:

if (input.matches("^(?!.*[.,]{2})[\\d.,]+))

This regex checks that:

  • dot and comma are never adjacent
  • input is comprised only of digits, dots and commas

To split:

String[] numbers = input.split("[.,]");

3 Comments

Thanks . Its working fine. Could you please help me to how to learn regexp easily.
sir, shouldn't numbers be an Array as split function returns an Array ?
@JDeveloper The best way to learn regex is to practice practice practice. Try answering regex questions here.
0

In order to separate the string, use split(), the argument of the method is the delimiter

array = string.split("separator");

2 Comments

split() requires the use of regular expressions, which is why I deleted my answer
First, have to check that the string is valid, then can use the split method, I think

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.