1

I want to split the input String values separated by one of these char

,
;
blankspace
\
/

in a double array

My code for , is

String valueS[] = input.split(",");
        int n = valueS.length;
        double yvalue[] = new double[n];
        double sum = 0;
        for (int i = 0; i < n; i++) {
            yvalue[i] = Double.parseDouble(valueS[i]);
        }

What is the right syntax that I should put in

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

to split also with the others listed chars?

1
  • split with ; and blankspace will work as same way it is right now working with , . but backslash and forward-slash will be tricky. Commented Apr 26, 2013 at 12:18

1 Answer 1

3

To actually answer your question, String.split (String regularExpression) uses a regular expression to determine what to split the array by.

This regular expression below will try to split the array by any one of these characters:

  • ,
  • ;
  • space
  • \
  • /

It is using an "Enumeration" that will match 1 or more of these characters in a row, and then split on them:

String[] valueS = input.split("[,;\\s\\\\/]+");

Hope this helps.

Sign up to request clarification or add additional context in comments.

14 Comments

No, it will split correctly, you appear to be struggling understanding how Strings escape characters. 1\2\3 = "1\\2\\3" in a String. "1\2\3" = 1[unseen character][unseen character]. I have just tested my suggested code and it works fine.
@MehulJoisar please read my comment above, I've already explained to you that you are escaping characters and not realizing they don't print. Please simply println "1\2\3" and you will see 1. This is because "\2" and "\3" are escaped, non-printable characters. When you run a split on "1\2\3", you should only see 1, this String you are testing with is invalid.
@MehulJoisar '\2' is a single character. There is no way to split it.
@MehulJoisar No, since "\2" and "\3" are their own characters, Octal Escapes. You are basically asking, how can I get "1", "2", "3" out of "1mn".
@MehulJoisar I would say it this way: "backslash converts itself and the next character to a different character at compile time".
|

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.