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.