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?
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 ).
Try Scanner instead of StringTokenizer
Scanner sc = new Scanner(str);
sc.useDelimiter("\\|");
while(sc.hasNext()) {
String e = sc.next();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.