4

I am trying to use simple split() method but the output I am getting is not Correct .I am using this code:

        question = newobject.ACTIVITY_LIST_OF_QUESTIONS.split("|");

where the newobject.ACTIVITY_LIST_OF_QUESTIONS contains 1|2|8|11|4|5|6|14|15|16|13|17|7|9|12|10 as a String so I must be getting each number in array index.

But instead of that I am getting output-

       1
       |
       2
       |
       8

Please help If someone had the same problem?

2
  • 1
    You can use String tokenizer to do the same Commented Feb 20, 2012 at 11:18
  • How are you printing your output? Commented Feb 20, 2012 at 11:20

3 Answers 3

3

You should use split("\\|"). You need to break the special meaning of the regex |. You do so with \\|. [Note that split() is splitting according to regex].

String s = "1|2|8|11|4|5|6|14|15|16|13|17|7|9|12|10";
String[] arr = s.split("\\|");
System.out.println(Arrays.toString(arr));

results in:

[1, 2, 8, 11, 4, 5, 6, 14, 15, 16, 13, 17, 7, 9, 12, 10]
Sign up to request clarification or add additional context in comments.

Comments

1

You need to escape | as \\|. Your regex is being interpreted as "empty string or empty string", so each position matches.

Comments

1

A | is a regex metacharacter used to denote alteration. To mean a literal | you need to escape it as \\| or put it in a character class [|].

Comments

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.