split(" ") in String " Java Essential " generates 3 tokens. Why?

Asked

Viewed 58 times

0

The idea was to separate words from whitespace. It follows the following code.

String s = " Java Essencial ";


String[] ss = s.split(" ");

for (int i = 0; i < ss.length; i++) {
    System.out.println("[" + i + "] " + ss[i]);
}

As seen in the result, we have three tokens. The correct one would not have 2 tokens?

1 answer

1


You have spaces at the beginning and end of String. To get the result you want (In case 2 pieces) you must use the method trim before performing the split:

String[] ss = s.trim().split(" ");

This will clear the spaces at the beginning and end of the String, ensuring the desired result.

Note also that you will have problems if there is more than one space separating words. In this case, in addition to trim() you can use a regular expression in conjunction with the replaceAll() to replace two or more spaces with just one. The expression would be [ ]{2,} and replace in your code we would have:

String[] ss = s.replaceAll("[ ]{2,}", " ").trim().split(" ");

trim()

Returns a copy of the string, with Leading and trailing whitespace omitted.

In free translation:

Returns the copy of the string, omitting the whitespace at the beginning and end.


replaceAll()

Replaces each substring of this string that Matches the Given regular Expression with the Given Replacement.

In free translation:

Replaces each substring of the string that matches the regular expression given by the given substitution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.