Java 空字符串的 String IndexOf 行为

Java String IndexOf behaviour for empty string

对于字符串来说,String str = "abc" str.indexOf("a")str.indexOf("") return 0。这种行为有效吗?

String.indexof("")的return值为0,也就是起始索引,当你传入一个空字符串时,因为空字符串"" 确实位于那里。 将 "abc" 视为 "" + "abc".

否则,请参考此文档:

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."

因此,str.indexOf("a") returns 0.

是的。概念上的原因与数学中加 0 非常相似。所以""+"a"+"bc" = "abc" = ""+"a"+"b"+""+"c".

要是有某个地方可以记录方法的行为就好了。

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.

把它想象成

"" +"abc"="abc"

基本上

"abc" is ""+"abc"

空字符串实际上存在于任何非空的字符串中。