I had found only StringComparison, but that's not working for Contains. Another necessary thing is ignoring case, and "ä" should equials to "a".
Asked
Active
Viewed 1.2k times
3 Answers
11
public static bool CustomContains(this string source, string toCheck)
{
CompareInfo ci = new CultureInfo("en-US").CompareInfo;
CompareOptions co = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace;
return ci.IndexOf(source, toCheck, co) != -1;
}

Joao Leme
- 9,598
- 3
- 33
- 47
-
Can't believe I had never heard of the CompareInfo class before ! – Rémy Esmery Apr 27 '16 at 09:39
-
1I was skeptical about this solution but it did handle the i, İ, ı and I characters properly (treated them as same). +1 – yasirkula Nov 23 '19 at 17:55
6
Internally string.Contains
use string.IndexOf passing a StringComparison.Ordinal
.
So I think that you could easily write a method that use the same implementation of Contains
public bool CaseContains(string baseString, string textToSearch, StringComparison comparisonMode)
{
return (baseString.IndexOf(textToSearch, comparisonMode) != -1);
}
and call with
if(CaseContains(myString, mySearch, StringComparison.CurrentCultureIgnoreCase))
....
an elegant evolution of this approach is to create an extension method
public static class StringExtensions
{
public static bool CaseContains(this string baseString, string textToSearch, StringComparison comparisonMode)
{
return (baseString.IndexOf(textToSearch, comparisonMode) != -1);
}
}
and call with
if(myString.CaseContains(mySearch, StringComparison.CurrentCultureIgnoreCase))
.....

Steve
- 213,761
- 22
- 232
- 286
-
2I believe, this is the most elegant solution. But StringComparison.CurrentCultureIgnoreCaseare is not recognizing "ä" as "a". – Vitalii Vasylenko Apr 27 '13 at 11:58
1
Thats an umlaut over the a. "ä" is not the same as "a". If you want to change it you need to do it explicitly.

Phil Murray
- 6,396
- 9
- 45
- 95
-
1Also, it's more common to replace `ä` with `ae` and `ö` with `oe` and so on. http://stackoverflow.com/questions/1271567/how-do-i-replace-accents-german-in-net If he wants to remove diacritics anyway: http://stackoverflow.com/a/7471047/284240 – Tim Schmelter Apr 26 '13 at 22:40
-
3// "ä" is not the same as "a". Usually they are not the same, but i need this for product search, so its better to show more results, i think. – Vitalii Vasylenko Apr 26 '13 at 22:51