How to compare l and ł (Polish character) in c# to return true

165 Views Asked by At

I am trying to compare the following two characters l and ł and get c# to return true

i.e. I have the word Przesyłka and would like to do a string comparison to Przesylka

I have tried the following but they all return false

public static void Main()
{
    Console.WriteLine("l".Equals("ł", StringComparison.InvariantCulture));
    Console.WriteLine("l".Equals("ł", StringComparison.Ordinal));
    Console.WriteLine("l".Equals("ł", StringComparison.OrdinalIgnoreCase));
    Console.WriteLine("l".Equals("ł", StringComparison.InvariantCultureIgnoreCase));
    Console.WriteLine("l".Equals(RemoveDiacritics("ł"), StringComparison.InvariantCulture));
}

//https://stackoverflow.com/a/368850/2987066
static string RemoveDiacritics(string text)
{
  return string.Concat( 
      text.Normalize(NormalizationForm.FormD)
      .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch)!=
                                    UnicodeCategory.NonSpacingMark)
    ).Normalize(NormalizationForm.FormC);
}

As you can see I also tried a workarond from this stackoverflow answer but it also returned false.

Is there a way to compare these two characters in c# in a way that returns true?

2

There are 2 best solutions below

3
shingo On BEST ANSWER

Try:

string.Compare("l", "ł", CultureInfo.InvariantCulture,
               CompareOptions.IgnoreNonSpace) == 0;

IgnoreNonSpace: Indicates that the string comparison must ignore nonspacing combining characters, such as diacritics.

3
Schamal On

I guess this is not the best solution, but if you really need to have this to be equal you could write a custom string EqualityComparer:


var equalsComparer = new EqualsComparer();
if (equalsComparer.Equals("Przesyłka", "Przesylka"))
{
    Console.WriteLine("true");
}
else
{
    Console.WriteLine("false");
}


class EqualsComparer : IEqualityComparer<string>
{
    public bool Equals(string? x, string? y)
    {
        x = x.Replace("ł", "L").ToLowerInvariant();
        y = y.Replace("ł", "L").ToLowerInvariant();

        return x.Equals(y);
    }

    public int GetHashCode([DisallowNull] string obj)
    {
        return obj.GetHashCode();
    }
}