Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split method of String class does not include trailing empty strings [duplicate]

Tags:

java

regex

Possible Duplicate:
Java split() method strips empty strings at the end?

The split method of String class does not include trailing empty strings in the array it returns. How do I get past this restriction:

class TestRegex{
 public static void main(String...args){
  String s = "a:b:c:";    
  String [] pieces = s.split(":");

  System.out.println(pieces.length); // prints 3...I want 4.
 }
}
like image 502
gameover Avatar asked Jan 31 '10 04:01

gameover


People also ask

Can you split an empty string?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

Can string split return empty array?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

What is split () function in string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Is string Tokenizer faster than split?

The split() method is preferred and recommended even though it is comparatively slower than StringTokenizer. This is because it is more robust and easier to use than StringTokenizer. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.


1 Answers

According to the documentation:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero.

For the split with the limit argument, it says:

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.

So, try to call the split method with a non-positive limit argument, like this:

String[] pieces = s.split(":", -1);
like image 87
Alex Ntousias Avatar answered Sep 30 '22 20:09

Alex Ntousias