谁能告诉我Objective C中不区分大小写比较的资料?它似乎没有与str1.equalsIgnoreCase(str2)等效的方法


当前回答

把Jason Coco的答案转换成Swift的懒人版:)

if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
  // Strings are equal.
}

其他回答

来检查iPhone ContactApp中的前缀

([string rangeOfString:prefixString options:NSCaseInsensitiveSearch].location == 0)

这个博客对我很有用

if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
  // strings are equal except for possibly case
}

文档位于搜索和比较方法

 NSString *stringA;
 NSString *stringB;

 if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
     // match
 }

注意:stringA &&是必需的,因为当stringA为nil时:

 stringA = nil;
 [stringA caseInsensitiveCompare:stringB] // return 0

所以NSOrderedSame也被定义为0。

下面的例子是一个典型的陷阱:

 NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
 if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
     // what happens if "Rank" is not found in standardUserDefaults
 }

试试这个方法

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString

一种新的方法。iOS 8

let string: NSString = "Café"
let substring: NSString = "É"

string.localizedCaseInsensitiveContainsString(substring) // true