IndexOf seems like a fairly straight forward method, it looks for the index of a character (or set of characters - aka. a string) and tells you the index of where it appears. If you look for the index of something that isn't there it usually returns
-1. (Usually because PHP and their
strpos method return
What if we did the
IndexOf an empty string - what do you think will happen?
Let's see if you guessed right...
It turns out if we do that, we get
Now for .NET, Microsoft does actually explain it a little:
Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. If value consists only of one or more ignorable characters, the IndexOf(String) method always returns 0 (zero) to indicate that the match is found at the beginning of the current instance.
This explanation though doesn't seem to explain why you would want it to return
0 for an empty string, just that it does.
I asked this on Twitter and Mateus mentioned a possible problem with it behaving this way.
Mateus Canello Ottoni@mattcanello@MrTurnerj I find it just strange. The answer I would expect is -1. In practice, charAt(0) won't return an empty string. Therefore, this behavior may lead to an inconsistent state.12:21 PM - 17 Aug 2019
While it might not be terribly often where you look for the index of a value and then compare that value from
charAt(0), it shows where the behaviour of finding the index can lead to weird results.
What are your thoughts about it - should it return
0 or maybe even throw an exception?
Do you know why it does this behaviour - let me know below!