Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String with multiple continuous comma in Java [duplicate]

Tags:

java

regex

split

String abc = "a,b,c,d,,,";
String[] arr = abc.split(",");
System.out.println(arr.length);

Output is 4. But obviously my expectation is 7. Here is my solution:

String abc = "a,b,c,d,,,";
abc += "\n";
String[] arr = abc.split(",");
System.out.println(arr.length);

Why does it happen? Anyone could give my a better solution?

like image 696
macemers Avatar asked Apr 15 '14 10:04

macemers


People also ask

How do I split a string into multiple spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

Can you use multiple delimiters in Java?

In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting strings into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space.

How do you split a comma separated string?

To split a string with comma, use the split() method in Java. str. split("[,]", 0); The following is the complete example.


3 Answers

Use the alternative version of String#split() that takes two arguments to achieve this:

String abc = "a,b,c,d,,,";
String[] arr = abc.split(",", -1);
System.out.println(arr.length);

This prints

7

From the Javadoc linked above:

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

like image 169
Keppil Avatar answered Nov 15 '22 00:11

Keppil


You can use lookahead:

String abc = "a,b,c,d,,,";
String[] arr = abc.split("(?=,)");
System.out.println(arr.length); //7
like image 44
anubhava Avatar answered Nov 14 '22 22:11

anubhava


Use:

String[] arr = abc.split("(?=,)");

to split abc

like image 20
betteroutthanin Avatar answered Nov 14 '22 23:11

betteroutthanin