Reputation: 6487
i think it is a weird question. So here is my splitting:
String s = "asd#asd";
String[] raw1 = s.split("#"); // this has size of two raw[0] = raw[1] = "asd"
However,
String s = "asd$asd";
String[] raw2 = s.split("$"); // this has size of ONE
raw2 is not splitted. Does anyone know why?
Upvotes: 0
Views: 115
Reputation: 272417
Because split()
takes a regexp, and $
indicates the end-of-line. If you need to split on a character that is actually a regexp metacharacter, then you'll need to escape it.
See Pattern for the regexp metacharacters.
You may find that StringTokenizer is more appropriate for your needs. This will take a list of characters that you should split on, and it won't interpret them as regular expression metacharacters. However it's a little more verbose and unweildy to use. As Nandkumar notes below, the latest docs states that it is discouraged in new code.
Upvotes: 5
Reputation: 2790
You have to escape it:
String s = "asd$asd";
String[] raw2 = s.split("\\$"); // this has size of TWO
Upvotes: 3
Reputation: 1589
Because split()
takes a regex and $
matches the end of a line.
You have to escape it :
s.split("\\$");
See Pattern documentation for more information on regexes.
Upvotes: 3
Reputation: 240966
You need to escape special character, make it
s.split("\\$");
Upvotes: 1