snippetcsharpCritical
How to make '.Contains(string)' case insensitive
Viewed 0 times
howinsensitivestringcasemakecontains
Problem
Is there a way to make the following return true?
There doesn't seem to be an overload that allows me to set the case sensitivity. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the i18n issues that come with up- and down casing).
string title = "ASTRINGTOTEST";
title.Contains("string");There doesn't seem to be an overload that allows me to set the case sensitivity. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the i18n issues that come with up- and down casing).
Solution
To test if the string
Where
This solution is transparent about the definition of case-insensitivity, which is language dependent. For example, the English language uses the characters
Thus the strings
To summarise, you can only answer the question 'are these two strings the same but in different cases' if you know what language the text is in. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to
paragraph contains the string word (thanks @QuarterMeister)culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0Where
culture is the instance of CultureInfo describing the language that the text is written in.This solution is transparent about the definition of case-insensitivity, which is language dependent. For example, the English language uses the characters
I and i for the upper and lower case versions of the ninth letter, whereas the Turkish language uses these characters for the eleventh and twelfth letters of its 29 letter-long alphabet. The Turkish upper case version of 'i' is the unfamiliar character 'İ'.Thus the strings
tin and TIN are the same word in English, but different words in Turkish. As I understand, one means 'spirit' and the other is an onomatopoeia word. (Turks, please correct me if I'm wrong, or suggest a better example)To summarise, you can only answer the question 'are these two strings the same but in different cases' if you know what language the text is in. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to
CultureInfo.InvariantCulture, because it will be wrong in familiar ways.Code Snippets
culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0Context
Stack Overflow Q#444798, score: 1587
Revisions (0)
No revisions yet.