salman khalid
salman khalid

Reputation: 4934

Split string in java for delimiter

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 ^.

Upvotes: 4

Views: 5670

Answers (4)

Sumit Singh
Sumit Singh

Reputation: 15886

You can use StringTokenizer instead of split

StringTokenizer st=new StringTokenizer(Your string,"^");  
while(st.hasMoreElements()){  
    System.out.println(st.nextToken());  
}  

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

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.

Upvotes: 12

Dante WWWW
Dante WWWW

Reputation: 2739

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.

Upvotes: 0

Narendra Yadala
Narendra Yadala

Reputation: 9664

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]

Upvotes: 2

Related Questions