Navdroid
Navdroid

Reputation: 4533

Error in output using split() method?

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?

Upvotes: 4

Views: 102

Answers (3)

codaddict
codaddict

Reputation: 454940

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 [|].

Upvotes: 1

amit
amit

Reputation: 178411

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]

Upvotes: 3

Dmitri
Dmitri

Reputation: 9157

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

Upvotes: 1

Related Questions