Reputation: 19
I'm having a weird problem with the IndexOf
function:
"strcat".IndexOf("st")
returned -1
"strcat".IndexOf("str")
returned 0
Can anyone explain why that happened?
Upvotes: 0
Views: 154
Reputation: 11801
It may be related to your system's current culture. Based on your name, I assumed Vietnamese.
System.Threading.Thread.CurrentThread.CurrentCulture = New Globalization.CultureInfo("vi-VN")
Dim i1 As Int32 = "strcat".IndexOf("st")
Dim i2 As Int32 = "strcat".IndexOf("str")
Dim i3 As Int32 = "strcat".IndexOf("st", System.StringComparison.InvariantCulture)
Dim i4 As Int32 = "strcat".IndexOf("str", System.StringComparison.InvariantCulture)
yields: i1 = -1, i2 = 0, i3 = 0, i4 = 0
Edited to this address question posed in the comments section.
How does this happen? I don't see anything the culture would change?
To answer this you should refer to the documentation for the method. see: String.IndexOf Method (String)
The relevant information is:
This method performs a word (case-sensitive and culture-sensitive) search using the current culture. The search begins at the first character position of this instance and continues until the last character position.
A given culture has its own rules for what is considered "common knowledge/pratice". You should not assume that what you consider normal is normal in a different culture. This is reason that the methods that perform comparisons allow you to specify a culture to define the rules used to perform the comparison.
This does not apply only to strings, but also dates.
The most famous programming conundrum is: Does your program pass the turkey test? Also known as the "Turkish-I problem". These are terms that you can research for more information.
Upvotes: 5