IndexOf 方法在 C# / Java 中本应返回 -1 时却返回 0

发布于 2024-08-28 01:31:38 字数 424 浏览 7 评论 0原文

我的一个朋友带着这种奇怪的行为来找我,我无法解释,任何有洞察力的观点将不胜感激。

我正在运行 VS 2005 (C# 2.0),以下代码显示了

int rr = "test".IndexOf("");
Console.WriteLine(rr.ToString());

上述代码的行为,打印“0”,这清楚地表明它应该返回 -1

这也发生在 Java 中,其中以下类显示了行为:

public class Test{
 public static void main(String[] args){
   System.out.println("Result->"+("test".indexOf("")));
 }
}

我正在运行 Java 1.6。 0_17

A friend of mine came to me with this strange behavior which i can't explain, any insight view would be appreciated.

Im running VS 2005 (C# 2.0), the following code show the behavior

int rr = "test".IndexOf("");
Console.WriteLine(rr.ToString());

the above code, print "0" which clearly show it should have return -1

This also happen in Java where the following Class show the behavior:

public class Test{
 public static void main(String[] args){
   System.out.println("Result->"+("test".indexOf("")));
 }
}

Im running Java 1.6.0_17

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

雨落□心尘 2024-09-04 01:31:38

引用自 C# 文档

如果值为,则返回值
是 0。

您描述的行为完全符合预期(至少在 C# 中)。

Quote from the C# documentation:

If value is Empty, the return value
is 0.

The behavior that you describe is entirely as expected (at least in C#).

预谋 2024-09-04 01:31:38

0 是正确的。从位置零开始,您可以(简单地)匹配零长度字符串。同样,“”包含“”。

0 is correct. Start at position zero and you can (trivially) match a zero-length string. Likewise, "" contains "".

少女净妖师 2024-09-04 01:31:38

这并不是规则的例外,而是 indexOfstartsWith 定义方式的自然结果。

您声称 "test".indexOf("") 应该返回 -1。这本质上相当于 "test".startsWith("") 应该返回 false 的声明。这是为什么呢?尽管这种情况在文档中被明确描述为返回 true,但这不仅仅是一个任意的决定。

例如,您将如何决定"test".startsWith("te")?最简单的方法是使用递归。由于两个字符串均以字符 't' 开头,因此您可以调用 "est".startsWith("e") 并返回结果。同样,您将调用 "st".startsWith("") 并返回结果。但您已经知道答案应该是 true,因此每个字符串都以 "" 开头。

This is not an exception to the rule, but rather a natural consequence of how indexOf and startsWith are defined.

You’re claiming that "test".indexOf("") should return -1. This is essentially equivalent to the claim that "test".startsWith("") should return false. Why is this? Although this case is specifically addressed in the documentation as returning true, this is not just an arbitrary decision.

How would you decide "test".startsWith("te"), for example? The simplest way is to use recursion. Since both strings start with the character 't', you call "est".startsWith("e") and return the result. Similarly, you will call "st".startsWith("") and return the result. But you already know that the answer should be true, so that is why every string starts with "".

沐歌 2024-09-04 01:31:38

0 是正确的。 Javadocs 指出 indexOf 的工作原理如下:

返回的整数是最小的
k 值使得:

 this.startsWith(str, k)

任何以 "" 开头的字符串都等于原始字符串(并且每个字符串都以 "" 开头),因此最小的 kstr = "" 的 code> 始终为 0。

0 is correct. The Javadocs point out that indexOf works as follows:

The integer returned is the smallest
value k such that:

 this.startsWith(str, k)

Any string starting with "" is equal to the original string (and every string starts with ""), so the smallest k for str = "" is always 0.

浅唱々樱花落 2024-09-04 01:31:38

可以这样想:IndexOf,在查找字符串时,会从位置 0 开始,尝试匹配该字符串,如果不匹配,则移动到位置 1、2 等。当你用空调用它时string,它尝试将空字符串与从位置 0 开始、长度为 0 的字符串进行匹配。万岁,无等于无。

旁注:当您使用 Console.Write/WriteLine 时,没有真正的理由使用 ToString。该函数自动调用相关对象的 ToString 方法。 (除非重载ToString)

Think of it this way: IndexOf, when looking for a string, will start at position 0, try to match the string, if it doesn't fit, move on to position 1, 2, etc. When you call it with an empty string, it attempts to match the empty string with the string starting at position 0 with length 0. And hooray, nothing equals nothing.

Side note: There's no real reason to use ToString when you're using Console.Write/WriteLine. The function automatically calls the ToString method of the object in question. (Unless overloading ToString)

迷荒 2024-09-04 01:31:38

它应该返回 0。您正在寻找空字符串的第一次出现,对吗? :)

It should return 0. You are looking for the first occurrence of an empty string, right? :)

北城孤痞 2024-09-04 01:31:38

更有趣的 php 实际上做得更好!

php -r "print strpos('test','');"
PHP Warning:  strpos(): Empty delimiter. in Command line code on line 1

More fun php actually does a way better job!

php -r "print strpos('test','');"
PHP Warning:  strpos(): Empty delimiter. in Command line code on line 1
我也只是我 2024-09-04 01:31:38

只是为了好玩。它也像 python 中那样工作,

>>> "test".startswith("")
True
>>> "test".index("")
0

Python 抛出一个 ValueError 而不是 -1,这很好。

>>> "test".index('r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

Just for the fun of it. It also works like that in python

>>> "test".startswith("")
True
>>> "test".index("")
0

Python throws a ValueError instead of the -1 that is nice.

>>> "test".index('r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文