问题
I have the string:
2|HOME ELECTRONICS| |0|0| | | | |0| |
I want to separate all tokens delimited by |
in the above string.
I tried to tokenize it with StringTokenizer
but it doesn't consider space as a token.
Also, I tried split("|")
but it gives each character of the above string as elements in returned string array.
What should I do?
回答1:
Try
string.split("\\|");
|
is a special character and must be espaced with escape character \
. In Java \
is written as \\
.
That is because String#split() takes regular expression as a parameter.
In a regex special chars like .
, |
, (
, etc must be escaped. Otherwise, Java will think you are actually using the special char (for example the |
means OR).
回答2:
Try Scanner instead of StringTokenizer
Scanner sc = new Scanner(str);
sc.useDelimiter("\\|");
while(sc.hasNext()) {
String e = sc.next();
}
来源:https://stackoverflow.com/questions/17148150/stringtokenizer-and-string-split-split-on-special-character