Home >Backend Development >C++ >How Can I Perform Case-Insensitive String Comparisons in C# While Ignoring Accented Characters?

How Can I Perform Case-Insensitive String Comparisons in C# While Ignoring Accented Characters?

DDD
DDDOriginal
2025-01-24 15:51:12311browse

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:

  1. Normalizes: Converts the input string to NormalizationForm.FormD, separating base characters and diacritics.
  2. Filters: Iterates through the characters, appending only those that aren't non-spacing marks (accents).
  3. Re-normalizes: Applies 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn