6

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 = "مباركُ وبعض أكثر من نص";
var word = "مبارك";
bool exist = text.Contains(word);
int index = text.IndexOf(word);

The results are the "exists = true" and "index = -1"

How can it be?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
gil kr
  • 2,190
  • 1
  • 17
  • 23
  • 1
    _I want to know if I found a bug.._ If you say this 100 times, probably you are wrong in 99 times :) – Soner Gönül Sep 11 '13 at 06:23
  • It seems `Contains` using `StringComparison.Ordinal` which returns true and `IndexOf` uses `StringComparison.CurrentCulture` by default. so returns `-1` – Sriram Sakthivel Sep 11 '13 at 06:29

1 Answers1

9

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!)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194