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 符号。如何处理?

4

1 回答 1

3

最后我找到了答案。

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

- (NSComparisonResult) compareTurkishSymbol:(unichar)ch with:(unichar)another
{
    if (ch == 305) {//code of 'ı'
      ch = 'i';  
    }
    return ch - another;
}
于 2012-02-16T10:16:49.743 回答