NSString比较特殊字符独立

时间:2013-03-28 22:26:46

标签: iphone objective-c macos cocoa nsstring

如何比较两个NSString,与字符无关?

NSPredicate提供==[d]比较器 但是我没有找到直接比较两个NSString的方法。


对于exapmle,这两个字符串应该被认为是相同的:

  

ŠämpléŠtrïñg

     

示例字符串

2 个答案:

答案 0 :(得分:3)

NSString *s1 = @"Šämplé Štrïñg";
NSString *s2 = @"Sample String";
NSComparisonResult cmp = [s1 compare:s2 options:NSDiacriticInsensitiveSearch];
// --> cmp = NSOrderedSame

答案 1 :(得分:2)

使用compare:options:

NSString *str1 = ...;
NSString *str2 = ...;
NSComparisonResult result = [str1 compare:str2 options:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch | NSWidthInsensitiveSearch];

如果您想对字符串执行其他操作,可以将两个字符串折叠为更简单的形式:

NSString *fold1 = [str1 stringByFoldingWithOptions:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch | NSWidthInsensitiveSearch locale:[NSLocale currentLocale]];
NSString *fold2 = [str2 stringByFoldingWithOptions:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch | NSWidthInsensitiveSearch locale:[NSLocale currentLocale]];
NSRange range = [fold1 rangeOfString:fold2]; // or other string comparisons