Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #213 Case-insensitive string compare

Compare four strings in pair-wise variations. The string comparison can be implemented with an equality test or a containment test, must be case-insensitive and must apply Unicode casefolding.

strings = ['ᾲ στο διάολο', 'ὰι στο διάολο', 'Ὰͅ ΣΤΟ ΔΙΆΟΛΟ', 'ᾺΙ ΣΤΟ ΔΙΆΟΛΟ']

strings.combination(2){|a,b| puts "#{a} equals #{b}: #{a.casecmp?(b)}" }
code (C) when $a =< C andalso C =< $z -> C - $a;
code (C) when $A =< C andalso C =< $Z -> C - $A;
code(C) -> C.

isSame([C | Rest1], [C | Rest2]) when is_integer(C)->
        isSame(Rest1, Rest2);
isSame([C1 | Rest1], [C2 | Rest2]) ->
        case (code(C1) - code(C2)) of
                0 -> isSame(Rest1, Rest2);
                _ -> false
        end;
isSame([], []) -> true;
isSame(_, _) -> false.
code (C) when $a =< C andalso C =< $z -> C - $a;
code (C) when $A =< C andalso C =< $Z -> C - $A;
code(C) -> C.

isSame([C | Rest1], [C | Rest2]) when is_integer(C)->
        isSame(Rest1, Rest2);
isSame([C1 | Rest1], [C2 | Rest2]) ->
        (code(C1) == code(C2)) andalso isSame(Rest1, Rest2);
isSame([], []) -> true;
isSame(_, _) -> false.
//no code here: see comments
use utf8;
use Test::More;
my @strings = ('ᾲ στο διάολο', 'ὰι στο διάολο', 'Ὰͅ ΣΤΟ ΔΙΆΟΛΟ', 'ᾺΙ ΣΤΟ ΔΙΆΟΛΟ');
my @indices = (
    [0,1], [0,2], [0,3],
    [1,0], [1,2], [1,3],
    [2,0], [2,1], [2,3],
    [3,0], [3,1], [3,2]
);
for my $tuple (@indices) {
    ok $strings[$tuple->[0]] =~ qr"\Q$strings[$tuple->[1]]"i;
}
done_testing;
import itertools
strings = ['ᾲ στο διάολο', 
           'ὰι στο διάολο', 
           'Ὰͅ ΣΤΟ ΔΙΆΟΛΟ', 
           'ᾺΙ ΣΤΟ ΔΙΆΟΛΟ']

for a, b in itertools.combinations(strings, 2):
    print(a, b, a.casefold() == b.casefold())
use itertools::Itertools;
for x in strings
    .iter()
    .combinations(2)
    .filter(|x| x[0].to_lowercase() == x[1].to_lowercase())
{
    println!("{:?} == {:?}", x[0], x[1])
}

New implementation...