Reputation: 172
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
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("\\|")
split("[|]")
.split(Pattern.quote("|"))
split("\\Q|\\E")
Upvotes: 7
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