Home >Backend Development >C++ >How Can I Perform Case-Insensitive String Comparisons in C# While Ignoring Accented Characters?
Case-Insensitive String Comparison in C# Ignoring Accents
C# string comparisons often require ignoring both case and accent marks. Standard options like StringComparison.InvariantCultureIgnoreCase
or StringComparison.OrdinalIgnoreCase
don't handle accented characters appropriately. This necessitates a custom solution for accurate comparisons.
Removing Diacritics (Accents)
The following function efficiently removes diacritics from strings:
<code class="language-csharp">static string RemoveAccents(string text) { string normalized = text.Normalize(NormalizationForm.FormD); StringBuilder sb = new StringBuilder(); foreach (char c in normalized) { if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) { sb.Append(c); } } return sb.ToString().Normalize(NormalizationForm.FormC); }</code>
This function:
NormalizationForm.FormD
, separating base characters and diacritics.NormalizationForm.FormC
for final cleanup.Implementing Case-Insensitive Comparison
To compare strings while ignoring case and accents, use RemoveAccents
and ToLowerInvariant()
before comparison:
<code class="language-csharp">string str1 = "Héllo"; string str2 = "Hello"; if (RemoveAccents(str1).ToLowerInvariant() == RemoveAccents(str2).ToLowerInvariant()) { // Strings are equal (ignoring case and accents) }</code>
This ensures a robust comparison that treats "Héllo" and "Hello" as identical. This method provides a flexible and accurate solution for case and accent-insensitive string comparisons in C#.
The above is the detailed content of How Can I Perform Case-Insensitive String Comparisons in C# While Ignoring Accented Characters?. For more information, please follow other related articles on the PHP Chinese website!