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?
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.
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.
To split a string with comma, use the split() method in Java. str. split("[,]", 0); The following is the complete example.
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.
You can use lookahead:
String abc = "a,b,c,d,,,";
String[] arr = abc.split("(?=,)");
System.out.println(arr.length); //7
Use:
String[] arr = abc.split("(?=,)");
to split abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With