Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : split a string that containing special characters

Tags:

java

string

regex

I have a string like ||81|||01|| and I want to split the string with | symbol.

I had done this way,

String str = "||81|||01||";
System.out.println(str .split("\\|").length); //printing 6 . But I am expecting 8

what is wrong with this code? | How can I split this string with that character so that I will get expected length (8)?;

like image 427
Dinoop paloli Avatar asked Apr 30 '13 10:04

Dinoop paloli


2 Answers

Using split("\\|") is the same as split("\\|", 0), where the limit parameter 0 tells the function "omit trailing empty strings". So you are missing the last two empty strings. Use the two-argument version and supply a negative number to obtain all parts (even trailing empty ones):

str.split("\\|", -1)
like image 75
Martin Ender Avatar answered Oct 04 '22 15:10

Martin Ender


Print:

System.out.println(Arrays.toString(str.split("\\|")));

And you'll understand why it's printing 6.

You can try doing what you want using public String[] split(String regex, int limit):

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

So you should do:

System.out.println(str.split("\\|", -1).length);

Now, printing the array will print:

[, , 81, , , 01, , ] as you expected.

like image 27
Maroun Avatar answered Oct 04 '22 15:10

Maroun