2

If you call IndexOf with the soft hyphen character as parameter, it will work as expected:

"aaa".IndexOf(Convert.ToChar(173)) // return -1
"aaa\u00AD".IndexOf(Convert.ToChar(173)) // return 3

However, if you call the exact same code using the soft hyphen as a string, the returned value will be 0 even if there's no soft hyphen in the string.

"aaa".IndexOf(Convert.ToChar(173).ToString()) // return 0
"aaa\u00AD".IndexOf(Convert.ToChar(173).ToString()) // return 0

Why does the IndexOf fails when you use a string?

The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
  • It would seem it treats a string with only a soft hyphen in it as an empty string (which is suppose to return 0). – juharr Apr 09 '20 at 21:00
  • 5
    It's because it's a zero width character, as explained here: https://stackoverflow.com/a/4893256/1658168 – Peter Dongan Apr 09 '20 at 21:09
  • 2
    Does this answer your question? [strange string.IndexOf behavour](https://stackoverflow.com/questions/4893216/strange-string-indexof-behavour) – kapsiR Apr 09 '20 at 21:23
  • why do you use `Convert.ToChar(173)` instead of `(char)173`? But better use `char.ConvertFromUtf32(173)` which returns a string directly and works for all Unicode values include ones outside the BMP – phuclv Apr 10 '20 at 01:48

0 Answers0