I don't see why does the following output makes sense.
String split method on an empty String returning an array of String with length 1
String[] split = "".split(",");
System.out.println(split.length);
Returns array of String with length 1
String[] split = "Java".split(",");
System.out.println(split.length);
Returns array of String with length 1
How to differentiate??
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.
Whenever there is a need to break bigger strings or a line into several small strings, you need to use the split() function in Python. The split() function still works if the separator is not specified by considering white spaces, as the separator to separate the given string or given line.
String. split(String) won't create regexp if your pattern is only one character long. When splitting by single character, it will use specialized code which is pretty efficient.
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.
From the documentation:
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.
To answer your question, it does what it is expected to do: the returned substring is terminated by the end of the input string (as there was no ,
to be found). The documentation also states:
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
Note that this is a consequence of the first statement. It is not an additional circumstance that the Java developers added in case the search string could not be found.
I hit this, too. What it's returning is the string up to but not including the split character. If you want to get no strings, use StringTokenizer:
StringTokenizer st = new StringTokenizer(someString,',');
int numberOfSubstrings = st.countTokens();
It's returning the original string (which in this case is the empty string) since there was no , to split on.
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