mlomb
mlomb

Reputation: 172

Java Split Error

I have this code:

String message = receiveMessage();
String[] reciv = message.split("|");

System.out.println("mess: " + message);
System.out.println("reciv: " + reciv[0]);

And this output:

mess: E|NAME
reciv: 

I look some strange, E|NAME is E|NAME*space**space**space**space**space**space**space*...

I try to copy the "spaces" and I can't. I'm thinking the "spaces" no are "spaces".

Sorry for my bad English, I'm Spanish.

Upvotes: 2

Views: 2712

Answers (2)

Pshemo
Pshemo

Reputation: 124215

split uses regex and in regex | has special meaning which is OR so "|" means empty string "" OR empty string "". Splitting on empty string means that

"ABC"

will split in these places (I will mark them with |)

"|A|B|C|"

producing array ["", "A", "B", "C", ""] but as split documentation says

Trailing empty strings are therefore not included in the resulting array

so last empty space is removed. So you get in result ["", "A", "B", "C"]


Now if you want make it | literal you need to escape it using for example

  • split("\\|")
  • or split("[|]").
  • or split(Pattern.quote("|"))
  • or split("\\Q|\\E")

Upvotes: 7

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You can do like this

String message = receiveMessage();
message  = message.replaceAll("[\n\r\\s]", "");
String[] str1 = message.split("[|]");
for (int i = 0; i < str1.length; i++) {
    System.out.println(str1[i]);
}

Upvotes: 2

Related Questions