StringTokenizer and String split - split on special character

橙三吉。 提交于 2019-12-24 10:46:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!