4

If I split "hello|" and "|hello" with "|" character, then I get one value for the first and two values for the second version.

String[] arr1 = new String("hello|").split("\\|");
String[] arr2 = new String("|hello").split("\\|");
System.out.println("arr1 length: " + arr1.length + "\narr2 length: " + arr2.length);

This prints out:

arr1 length: 1
arr2 length: 2

Why is this?

4
  • 1
    split(String regex) - This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. Commented Jul 20, 2015 at 12:40
  • Check this stackoverflow.com/questions/15113272/… Commented Jul 20, 2015 at 12:44
  • also check this Commented Jul 20, 2015 at 12:46
  • I had a code like str.contains("foo") ? str.split("foo")[1] : "" in production and it crashed because of this Commented May 20, 2024 at 13:12

4 Answers 4

10

According to java docs. split creates an empty String if the first character is the separator, but doesn't create an empty String (or empty Strings) if the last character (or consecutive characters) is the separator. You will get the same behavior regardless of the separator you use.

Sign up to request clarification or add additional context in comments.

3 Comments

"You will get the same behavior regardless of the separator you use" that depends on Java version. In pre 8 when we used split("") we always end up with empty string at start, but now (in Java 8) we don't (same with other zero-length regexes).
@Pshemo Interesting. I didn't know that. Thanks.
3

Trailing empty String will not be included in array check the following statement.

String#split This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Comments

1

String#split always returns the array of strings computed by splitting this string around matches of the given regular expression.

Comments

1

Check the source code for the answer: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/regex/Pattern.java#Pattern.compile%28java.lang.String%29

The last lines contains the answer:

int resultSize = matchList.size();
if (limit == 0)
  while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
    resultSize--;
String[] result = new String[resultSize];

So the end will not be included if it is empty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.