IndexOf method returns 0 when it should had return -1 in C# / Java

前端 未结 8 540
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 10:47

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

8条回答
  •  隐瞒了意图╮
    2021-01-12 11:28

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

提交回复
热议问题