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

前端 未结 8 693
被撕碎了的回忆
被撕碎了的回忆 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:24

    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)

提交回复
热议问题