Wielkość liter jest niewrażliwa "Contains(string)"

Czy istnieje sposób, aby następujący powrót był prawdziwy?

string title = "ASTRINGTOTEST";
title.Contains("string");

Nie wydaje się być przeciążenie, które pozwala mi ustawić czułość na wielkość liter.. Obecnie piszę je wielkimi literami, ale to jest po prostu głupie (przez co mam na myśli problemy i18n, które przychodzą z obudową w górę iw dół).

UPDATE
To pytanie jest starożytne i od tego czasu zdałem sobie sprawę, że poprosiłem o prostą odpowiedź na naprawdę rozległy i trudny temat, jeśli zależy ci na zbadaj to dokładnie.
W większości przypadków, w monojęzycznych, angielskich bazach kodu ta odpowiedź wystarczy. Podejrzewam, że większość osób tu przyjeżdżających zalicza się do tej kategorii. to jest najpopularniejsza odpowiedź.
Ta odpowiedź wywołuje jednak nieodłączny problem, że nie możemy porównywać wielkości tekstu bez rozróżnienia, dopóki nie dowiemy się, że oba teksty są tą samą kulturą i wiemy, czym jest ta kultura. To może mniej popularna odpowiedź, ale myślę, że jest bardziej poprawna i dlatego oznaczone jako takie.

Author: Neuron, 2009-01-14

28 answers

Aby sprawdzić, czy łańcuch paragraph zawiera łańcuch word (dzięki @QuarterMeister)

culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0

Gdzie culture jest instancją CultureInfo opisujący język, w którym tekst jest napisany.

To rozwiązanie jest przejrzyste o definicji niewrażliwości na przypadki, która jest zależna od języka. Na przykład, język angielski używa znaków I i i dla górnej i dolnej wersji dziewiątej litery, podczas gdy Język turecki używa te znaki dla jedenastej i dwunastej litery jego 29-literowego alfabetu. Turecka wersja litery " i "jest nieznanym znakiem "I".

Tak więc ciągi tin i TIN są tym samym słowem w języku angielskim, ale różnymi słowami w języku tureckim. Jak rozumiem, jedno oznacza "ducha", a drugie jest słowem onomatopei. (Turcy, popraw mnie, jeśli się mylę, lub zaproponuj lepszy przykład)

Podsumowując, możesz odpowiedzieć tylko na pytanie "czy te dwa ciągi są takie same, ale w różnych przypadkach" jeśli wiesz, w jakim języku jest tekst. Jeśli nie wiesz, będziesz musiał spróbować. Biorąc pod uwagę hegemonię angielskiego w oprogramowaniu, prawdopodobnie powinieneś uciekać się do CultureInfo.InvariantCulture, bo to będzie złe w znajomy sposób.

 1468
Author: Colonel Panic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-10 12:06:38

Możesz użyć String.IndexOf Method and pass StringComparison.OrdinalIgnoreCase jako typ wyszukiwania do użycia:

string title = "STRING";
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;

Jeszcze lepsze jest zdefiniowanie nowej metody rozszerzenia dla ciągu znaków:

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source?.IndexOf(toCheck, comp) >= 0;
    }
}

Zauważ, że propagacja zerowa ?. jest dostępny od C # 6.0 (VS 2015), dla starszych wersji używać

if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;

Użycie:

string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);
 2805
Author: JaredPar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-08 12:57:07

Możesz użyć IndexOf() w następujący sposób:

string title = "STRING";

if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
    // The string exists in the original
}

Ponieważ 0 (zero) może być indeksem, sprawdzasz przed -1.

MSDN

Pozycja indeksowana od zera wartości, jeśli ten łańcuch zostanie znaleziony, lub -1 jeśli nie. If value is String.Empty, zwracana wartość to 0.

 241
Author: mkchandler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-15 15:45:31

Alternatywne rozwiązanie przy użyciu Regex:

bool contains = Regex.IsMatch("StRiNG to search", Regex.Escape("string"), RegexOptions.IgnoreCase);
 154
Author: Jed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-17 09:18:03

Zawsze można po prostu up lub downcase struny pierwszy.

string title = "string":
title.ToUpper().Contains("STRING")  // returns true
UPS, właśnie widziałem ten ostatni kawałek. Porównanie bez rozróżniania wielkości liter i tak zrobiłoby to samo, a jeśli wydajność nie jest problemem, nie widzę problemu z tworzeniem wielkich kopii i porównywaniem ich. Mógłbym przysiąc, że kiedyś widziałem nieczułe porównanie...
 89
Author: Ed S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-14 21:54:21

. NET Core 2.0 + only (od teraz)

[[3]}. Net Core ma parę metod, aby poradzić sobie z tym od wersji 2.0:
  • String.Contains(Char, StringComparison)
  • String.Contains(String, StringComparison)

Przykład:

"Test".Contains("test", System.StringComparison.CurrentCultureIgnoreCase);

Z czasem prawdopodobnie trafią do standardu. NET, a stamtąd do wszystkich innych implementacji biblioteki klas bazowych.

 79
Author: Mathieu Renda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-08 14:49:03

Problem z odpowiedzią polega na tym, że wyrzuci wyjątek, jeśli łańcuch jest null. Możesz to dodać jako czek więc nie będzie:

public static bool Contains(this string source, string toCheck, StringComparison comp)
{
    if (string.IsNullOrEmpty(toCheck) || string.IsNullOrEmpty(source))
        return true;

    return source.IndexOf(toCheck, comp) >= 0;
} 
 54
Author: FeiBao 飞豹,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-05 06:02:45

Klasa StringExtension jest drogą naprzód, połączyłem kilka postów powyżej, aby dać pełny przykład kodu:

public static class StringExtensions
{
    /// <summary>
    /// Allows case insensitive checks
    /// </summary>
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source.IndexOf(toCheck, comp) >= 0;
    }
}
 39
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-25 06:58:32

To jest czyste i proste.

Regex.IsMatch(file, fileNamestr, RegexOptions.IgnoreCase)
 36
Author: takirala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-06 14:54:20

Zwykła, aktualna czy niezmienna?

Ponieważ tego brakuje, oto kilka zaleceń, kiedy użyć którego:

Dos

  • użyj StringComparison.OrdinalIgnoreCase do porównań jako Bezpieczne domyślne dopasowanie ciągów kulturowo-agnostycznych.
  • użyj StringComparison.OrdinalIgnoreCase porównania dla zwiększenia prędkości.
  • Use StringComparison.CurrentCulture-based string operations podczas wyświetlania danych wyjściowych użytkownikowi.
  • Switch current use of string operations na podstawie niezmiennika kultury, aby używać nie-lingwistycznych StringComparison.Ordinal lub StringComparison.OrdinalIgnoreCase, gdy porównanie jest
    bez znaczenia językowego (np. symbolicznego).
  • użyj ToUpperInvariant zamiast ToLowerInvariant, gdy normalizacja ciągów do porównania.

Don ' ts

  • użyj przeciążeń dla operacji ciągów znaków, które nie są jawnie lub pośrednio określa mechanizm porównywania łańcuchów.
  • Use StringComparison.InvariantCulture -based string
    operacje w większości przypadków; jednym z nielicznych wyjątków byłoby be
    utrzymujące się dane lingwistyczne, ale kulturowo-agnostyczne.

Na podstawie tych zasad należy użyć:

string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.[YourDecision]) != -1)
{
    // The string exists in the original
}

Podczas Gdy [twoja decyzja] zależy od zaleceń z góry.

Link źródła: http://msdn.microsoft.com/en-us/library/ms973919.aspx

 31
Author: Fabian Bigler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-23 10:30:30

Są to najprostsze rozwiązania.

  1. Według indeksu

    string title = "STRING";
    
    if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        // contains 
    }
    
  2. Zmieniając wielkość liter

    string title = "STRING";
    
    bool contains = title.ToLower().Contains("string")
    
  3. By Regex

    Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);
    
 25
Author: LAV VISHWAKARMA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 09:25:53

Jak proste i działa

title.ToLower().Contains("String".ToLower())
 14
Author: Pradeep Asanka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-10 22:32:51

Tak po prostu:

string s="AbcdEf";
if(s.ToLower().Contains("def"))
{
    Console.WriteLine("yes");
}
 13
Author: cdytoby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-19 19:23:43

Wiem, że to nie jest C#, ale w frameworku (VB.NET) istnieje już taka funkcja

Dim str As String = "UPPERlower"
Dim b As Boolean = InStr(str, "UpperLower")

C# variant:

string myString = "Hello World";
bool contains = Microsoft.VisualBasic.Strings.InStr(myString, "world");
 12
Author: serhio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-09 13:55:07

Metoda InStr z zestawu VisualBasic jest najlepsza, jeśli masz obawy o internacjonalizację (lub możesz ją ponownie zaimplementować). Patrząc w nim dotNeetPeek pokazuje, że nie tylko uwzględnia wielkie i małe litery, ale także znaki typu kana i znaki o pełnej lub pół szerokości (głównie istotne dla języków azjatyckich, chociaż istnieją również wersje alfabetu Rzymskiego o pełnej szerokości). Pomijam kilka szczegółów, ale sprawdź metodę prywatną InternalInStrText:

private static int InternalInStrText(int lStartPos, string sSrc, string sFind)
{
  int num = sSrc == null ? 0 : sSrc.Length;
  if (lStartPos > num || num == 0)
    return -1;
  if (sFind == null || sFind.Length == 0)
    return lStartPos;
  else
    return Utils.GetCultureInfo().CompareInfo.IndexOf(sSrc, sFind, lStartPos, CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth);
}
 12
Author: Casey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-06 14:11:23

Użyj tego:

string.Compare("string", "STRING", new System.Globalization.CultureInfo("en-US"), System.Globalization.CompareOptions.IgnoreCase);
 10
Author: mr.martan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-08 08:10:58

Jest to dość podobne do innych przykładów tutaj, ale zdecydowałem się uprościć enum do bool, primary, ponieważ inne alternatywy zwykle nie są potrzebne. Oto mój przykład:

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, bool bCaseInsensitive )
    {
        return source.IndexOf(toCheck, bCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;
    }
}

A użycie to coś w stylu:

if( "main String substring".Contains("SUBSTRING", true) )
....
 7
Author: TarmoPikaro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-17 07:46:58

Użycie RegEx jest prostą drogą do tego:

Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);
 7
Author: Stend,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-19 19:23:19

Aby zbudować odpowiedź tutaj, możesz utworzyć metodę rozszerzenia łańcucha znaków, aby uczynić ją bardziej przyjazną dla użytkownika:

    public static bool ContainsIgnoreCase(this string paragraph, string word)
    {
        return CultureInfo.CurrentCulture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0;
    }
 6
Author: Christian Findlay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-22 04:42:04

Możesz użyć parametru porównywania łańcuchów (dostępnego w. Net 2.1 i nowszych) String.Zawiera Metodę .

public bool Contains (string value, StringComparison comparisonType);

Przykład:

string title = "ASTRINGTOTEST";
title.Contains("string", StringComparison.InvariantCultureIgnoreCase);
 5
Author: dashrader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-23 20:39:41

Jeśli chcesz sprawdzić, czy przekazywany łańcuch jest w łańcuchu, to istnieje na to prosta metoda.

string yourStringForCheck= "abc";
string stringInWhichWeCheck= "Test abc abc";

bool isContained = stringInWhichWeCheck.ToLower().IndexOf(yourStringForCheck.ToLower()) > -1;

Ta wartość logiczna zwróci, jeśli łańcuch jest zawarty lub nie

 4
Author: shaishav shukla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-12 08:00:55
if ("strcmpstring1".IndexOf(Convert.ToString("strcmpstring2"), StringComparison.CurrentCultureIgnoreCase) >= 0){return true;}else{return false;}
 3
Author: Tamilselvan K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-26 14:34:14

Możesz użyć funkcji string.indexof (). To będzie niewrażliwe na wielkość liter

 3
Author: Okan SARICA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-11 13:41:20

Sztuczka polega na szukaniu łańcucha, ignorując wielkość liter, ale zachowując go dokładnie tak samo (z tą samą wielkością liter).

 var s="Factory Reset";
 var txt="reset";
 int first = s.IndexOf(txt, StringComparison.InvariantCultureIgnoreCase) + txt.Length;
 var subString = s.Substring(first - txt.Length, txt.Length);

Wyjście To "Reset"

 3
Author: Mr.B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 15:16:18

Podobne do poprzednich odpowiedzi (używając metody rozszerzenia), ale z dwoma prostymi kontrolami null (C # 6.0 i wyżej):

public static bool ContainsIgnoreCase(this string source, string substring)
{
    return source?.IndexOf(substring ?? "", StringComparison.OrdinalIgnoreCase) >= 0;
}

Jeśli source to null, zwróć false (za pomocą operatora propagacji null ?.)

Jeśli substring jest null, traktuj jako pusty łańcuch i zwracaj true (za pomocą operatora null-coalescing??)

StringComparison można oczywiście wysłać jako parametr w razie potrzeby.

 2
Author: Udi Y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-13 12:02:26
public static class StringExtension
{
    #region Public Methods

    public static bool ExContains(this string fullText, string value)
    {
        return ExIndexOf(fullText, value) > -1;
    }

    public static bool ExEquals(this string text, string textToCompare)
    {
        return text.Equals(textToCompare, StringComparison.OrdinalIgnoreCase);
    }

    public static bool ExHasAllEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index]) == false) return false;
        return true;
    }

    public static bool ExHasEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index])) return true;
        return false;
    }

    public static bool ExHasNoEquals(this string text, params string[] textArgs)
    {
        return ExHasEquals(text, textArgs) == false;
    }

    public static bool ExHasNotAllEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index])) return false;
        return true;
    }

    /// <summary>
    /// Reports the zero-based index of the first occurrence of the specified string
    /// in the current System.String object using StringComparison.InvariantCultureIgnoreCase.
    /// A parameter specifies the type of search to use for the specified string.
    /// </summary>
    /// <param name="fullText">
    /// The string to search inside.
    /// </param>
    /// <param name="value">
    /// The string to seek.
    /// </param>
    /// <returns>
    /// The index position of the value parameter if that string is found, or -1 if it
    /// is not. If value is System.String.Empty, the return value is 0.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    /// fullText or value is null.
    /// </exception>
    public static int ExIndexOf(this string fullText, string value)
    {
        return fullText.IndexOf(value, StringComparison.OrdinalIgnoreCase);
    }

    public static bool ExNotEquals(this string text, string textToCompare)
    {
        return ExEquals(text, textToCompare) == false;
    }

    #endregion Public Methods
}
 0
Author: Final Heaven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-14 03:16:07

Bazując na istniejących odpowiedziach i na dokumentacji metody Contains polecam utworzenie następującego rozszerzenia, które zajmuje się również przypadkami narożnymi:

public static class VStringExtensions 
{
    public static bool Contains(this string source, string toCheck, StringComparison comp) 
    {
        if (toCheck == null) 
        {
            throw new ArgumentNullException(nameof(toCheck));
        }

        if (source.Equals(string.Empty)) 
        {
            return false;
        }

        if (toCheck.Equals(string.Empty)) 
        {
            return true;
        }

        return source.IndexOf(toCheck, comp) >= 0;
    }
}
 0
Author: Valentin Peta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-29 10:06:35

Prosty sposób dla początkujących:

title.ToLower().Contains("string");//of course "string" is lowercase.
 -3
Author: O Thạnh Ldt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-23 03:33:44