Split string in java for delimiter

心不动则不痛 提交于 2019-12-07 09:38:54

问题


My question is that I want to split string in java with delimiter ^. And syntax which I am using is:

readBuf.split("^");

But this does not split the string.Infact this works for all other delimiters but not for ^.


回答1:


split uses regular expressions (unfortunately, IMO). ^ has special meaning in regular expressions, so you need to escape it:

String[] bits = readBuf.split("\\^");

(The first backslash is needed for Java escaping. The actual string is just a single backslash and the caret.)

Alternatively, use Guava and its Splitter class.




回答2:


Use \\^. Because ^ is a special character indicating start of line anchor.

String x = "a^b^c";
System.out.println(Arrays.toString(x.split("\\^"))); //prints [a,b,c]



回答3:


Or u can Use... StringTokenizer instead of split
StringTokenizer st=new StringTokenizer(Your string,"^");
while(st.hasMoreElements()){
System.out.println(st.nextToken());
}




回答4:


You can also use this:

readBuf.split("\\u005E");

the \u005E is the hexidecimal Unicode character for "^", and you need to add a "\" to escape it.

All characters can be escaped in this way.



来源:https://stackoverflow.com/questions/7925726/split-string-in-java-for-delimiter

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