Split string in java for delimiter

My question is that I want to split a string in java with a ^ delimiter. And the syntax that I use:

 readBuf.split("^"); 

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

+4
source share
4 answers

split uses regular expressions (unfortunately IMO). ^ is of particular importance in regular expressions, so you need to avoid it:

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

(The first backslash is needed to escape Java. The actual line is just one backslash and caret.)

Alternatively, use the Guava and Splitter class.

+12
source

Use \\^ . Because ^ is a special character indicating the start of a string binding.

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

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

0
source

You can also use this:

 readBuf.split("\\u005E"); 

the \ u005E is the Unicode hexadecimal character for "^", and you need to add "\" to avoid it.

All characters can be escaped in this way.

0
source

All Articles