gpt4 book ai didi

Java String.indexOf 和空字符串

转载 作者:IT老高 更新时间:2023-10-28 20:50:24 26 4
gpt4 key购买 nike

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

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

对我来说,这种行为似乎非常出乎意料,我本以为是 -1。任何想法为什么会发生这种意外行为?我至少认为这在方法的 Javadocs 中值得一提……

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?

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

关于Java String.indexOf 和空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2683466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com