Why are String.IndexOf and String.Contains disagreeing when provided with Arabic text?

前端 未结 1 455
执念已碎
执念已碎 2021-01-18 10:51

I want to know if I found a bug in the .NET Framework, or if I don\'t understand something. After running this piece of code:

var text = \"مباركُ وبعض أكثر م         


        
1条回答
  •  迷失自我
    2021-01-18 11:29

    Contains is culture-insensitive:

    This method performs an ordinal (case-sensitive and culture-insensitive) comparison.

    IndexOf is culture-sensitive:

    This method performs a word (case-sensitive and culture-sensitive) search using the current culture.

    That's the difference. If you use

    int index = text.IndexOf(word, StringComparison.Ordinal);
    

    then you'll get an index of 0 instead of -1 (so it's consistent with Contains).

    There's no culture-sensitive overload of Contains; it's unclear to me whether you can use IndexOf reliably for this, but the CompareInfo class gives some more options. (I really don't know much about the details of cultural comparisons, particularly with RTL text. I just know it's complicated!)

    0 讨论(0)
提交回复
热议问题