Bassant Ashraf Bassant Ashraf - 2 months ago 18
iOS Question

Compare arabic strings with special characters ios

When comparing two arabic strings that have special characters like
"إ " "أ"
The comparison always fail

NSString* string1 = @"الإجمالي";
NSString* string2 = @"الإجمالي";

BOOL ifEqual ;

if([string1 isEqualToString:string2]){
ifEqual = YES;
}else{
ifEqual = NO; //Answer is NO
}

Answer

The two strings contain the "إ" character in a different representation: The first string as one character ("precomposed representation"):

U+0625 ARABIC LETTER ALEF WITH HAMZA BELOW

and the second string as two characters ("decomposed representation")

U+0627 ARABIC LETTER ALEF
U+0655 ARABIC HAMZA BELOW

If you convert both strings to the precomposed representation then they compare as equal:

NSString* string1 = @"الإجمالي";
NSString* string2 = @"الإجمالي";

string1 = string1.precomposedStringWithCanonicalMapping;
string2 = string2.precomposedStringWithCanonicalMapping;

BOOL ifEqual ;

if ([string1 isEqualToString:string2]) {
    ifEqual = YES; //Answer is YES
} else {
    ifEqual = NO;
}

Swift string comparison handles that automatically:

let string1 = "الإجمالي"
let string2 = "الإجمالي"

print(string1 == string2)
// true