For a string say, String str = "abc" both str.indexOf("a") and str.indexOf("") return 0. Is this behaviour valid?
-
2possible duplicate of Java String.indexOf and empty Stringskirbyquerby– kirbyquerby2015-01-02 01:35:23 +00:00Commented Jan 2, 2015 at 1:35
-
What do you mean with valid? Do you imply there isn't a sequence of 0 characters at the very start of the string?Robert– Robert2015-01-02 01:45:14 +00:00Commented Jan 2, 2015 at 1:45
-
@Robert, My thought was suppose the search pattern is from an external source and let the pattern be "empty string". Now if I try to see the matched part I get first character instead of empty string.Viswanadh Kumar Reddy Vuggumud– Viswanadh Kumar Reddy Vuggumud2015-01-02 01:54:16 +00:00Commented Jan 2, 2015 at 1:54
-
@ViswanadhKumarReddyVuggumud Oh, but the matched part always equals the pattern. In particular the pattern and the matched part are of the same length. So you always have to check the length of the pattern, it might also be longer than 1 character.Robert– Robert2015-01-02 01:59:57 +00:00Commented Jan 2, 2015 at 1:59
-
@Robert I agree, not that it is serious but my point is it would make have made much better sense if the other way of finding the matching part is also true :)Viswanadh Kumar Reddy Vuggumud– Viswanadh Kumar Reddy Vuggumud2015-01-02 02:08:03 +00:00Commented Jan 2, 2015 at 2:08
5 Answers
If only there was some place where they document behaviour of methods.
indexOf(string)
Returns the index within this string of the first occurrence of the specified substring. The returned index is the smallest value k for which:
this.startsWith(str, k)
startsWith(string)
true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.
Comments
The return value of String.indexof("") is 0, or the starting index, when you pass in an empty string because the empty string "" is indeed located there.
Think of "abc" as "" + "abc".
Otherwise, please refer to this documentation:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
indexOf "returns:the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur."
Therefore, str.indexOf("a") returns 0.