Java String.indexOf和空字符串

Java String.indexOf and empty Strings

我很好奇为什么String.indexOf在查询字符串中的空字符串的索引时返回0(而不是-1)。

Javadocs仅说此方法返回指定字符串在此字符串中的索引,如果找不到该字符串,则返回-1。

在我看来,这种行为是非常出乎意料的,我期望值为-1。 有什么想法为什么这种意外的行为会继续吗? 我至少认为这值得在该方法的Javadocs中进行说明...

1
2
3
4
System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think


空字符串无处不在,无处不在。它始终存在于所有字符串中,渗透着它们的本质,但是当您寻求它时,您将永远不会瞥见。

一个字符串的开头可以容纳多少个空字符串?亩

学生对老师说:

Teacher, I believe that I have found the nature of the empty string. The empty string is like a particle of dust, and it floats freely through a string as dust floats freely through the room, glistening in a beam of sunlight.

老师回应学生,

Hmm. A fine notion. Now tell me, where is the dust, and where is the sunlight?

老师用皮带打学生,并指示他继续冥想。


好吧,如果有帮助,您可以将"FOO"视为"" +"FOO"


int number_of_empty_strings_in_string_named_text = text.length() + 1

所有字符都用空的String分隔。另外,在开头和结尾都存在空String


使用代数方法,"是字符串连接的中性元素:x +" == x和" + x == x(尽管+在这里是不可交换的)。

那么它还必须是:

1
2
x.indexOf ( y ) == i and i != -1
<==> x.substring ( 0, i ) + y + x.substring ( i + y.length () ) == x

当y ="时,如果i == 0且x.substring(0,0)==",则成立。
我没有设计Java,但是我猜数学家参加了它。


通过使用表达式",您实际上是在指一个空字符串。空字符串是放置在存在的东西上的空灵标记,仅表明该位置没有任何东西。

因此,通过说" .indexOf("),您实际上是在询问解释器:

null字符串中的null值哪里存在?

它返回零,因为null在不存在的null字符串的开头。

现在,向字符串添加任何内容将使其成为非null字符串... null可以被视为缺少所有内容,甚至没有任何内容。