Objective-C中unichar的比较

3

我需要实现一种方法,用于比较两个字符串的相等性,考虑到某些土耳其字母被视为拉丁字母(例如:ı = i)。这是程序中的瓶颈,因此需要尽可能高效地实现。

我不能使用NSString compare: withOption:nsdiactricinsensitivesearch,因为它无法正确处理土耳其字母。

以下是我的算法实现:

- (NSComparisonResult) compareTurkishSymbol:(unichar)ch with:(unichar)another
{
    //needs to be implemented
    //code like: if (ch == 'ı') doesn't work correctly
}

- (NSComparisonResult)compareTurkish:(NSString*)word with:(NSString*)another
{
    NSUInteger i;
    for (i =0; i < word.length; ++i) {
        NSComparisonResult result =[self compareTurkishSymbol:[word characterAtIndex:i] with:[another characterAtIndex:i]];
        if (result != NSOrderedSame) {
            return result;
        }
    }

    return another.length > word.length ? NSOrderedDescending : NSOrderedSame;
}

问题在于我无法正确比较unichars。它不能正确比较非ASCII符号。如何解决这个问题?


看起来是重复的:https://dev59.com/O1vUa4cB1Zd3GeqPyOyE - lqez
不行。我不能使用NSDiacriticInsensitiveSearch,因为它无法处理所有土耳其非拉丁符号。 - Rustam Ganeyev
我已经找到了解决方案。我可以通过符号代码进行检查,并将其作为整数进行比较。 - Rustam Ganeyev
1个回答

3

最终我找到了答案。

unichar是无符号短整型,这意味着每个符号都有其代码。因此,我们可以将它们作为数字而不是字符进行比较。

- (NSComparisonResult) compareTurkishSymbol:(unichar)ch with:(unichar)another
{
    if (ch == 305) {//code of 'ı'
      ch = 'i';  
    }
    return ch - another;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接