方法名
- (NSComparisonResult)compare:(NSString *)string;
方法作用:
- (NSComparisonResult)compare:(NSString *)string;
主要理解如下属性:
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
NSCaseInsensitiveSearch = 1, /*忽略大小写*/
NSLiteralSearch = 2, /* 不忽略大小写 */
NSBackwardsSearch = 4, /* 从后往前比较 */
NSAnchoredSearch = 8, /* Search is limited to start (or end, if NSBackwardsSearch) of source string */
NSNumericSearch = 64, /*常见 版本号比较 Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */
NSDiacriticInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 128, /* If specified, ignores diacritics (o-umlaut == o) */
NSWidthInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 256, /* If specified, ignores width differences ('a' == UFF41) */
NSForcedOrderingSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 512, /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */
NSRegularExpressionSearch API_AVAILABLE(macos(10.7), ios(3.2), watchos(2.0), tvos(9.0)) = 1024 /* 正则 Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */
};
官方文档链接:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/SearchingStrings.html#//apple_ref/doc/uid/20000149-CJBBGBAI
compare 标准 unicode
指定比较option: eg.NSNumericSearch
apple Demo:
Comparing Strings
The following examples illustrate the use of various string comparison methods and associated options. The first shows the simplest comparison method.
NSString *string1 = @"string1"; |
NSString *string2 = @"string2"; |
NSComparisonResult result; |
result = [string1 compare:string2]; |
// result = -1 (NSOrderedAscending) |
You can compare strings numerically using the NSNumericSearch
option:
NSString *string10 = @"string10"; |
NSString *string2 = @"string2"; |
NSComparisonResult result; |
|
result = [string10 compare:string2]; |
// result = -1 (NSOrderedAscending) |
|
result = [string10 compare:string2 options:NSNumericSearch]; |
// result = 1 (NSOrderedDescending) |
You can use convenience methods (caseInsensitiveCompare:
and localizedCaseInsensitiveCompare:
) to perform case-insensitive comparisons:
NSString *string_a = @"Aardvark"; |
NSString *string_A = @"AARDVARK"; |
|
result = [string_a compare:string_A]; |
// result = 1 (NSOrderedDescending) |
|
result = [string_a caseInsensitiveCompare:string_A]; |
// result = 0 (NSOrderedSame) |
// equivalent to [string_a compare:string_A options:NSCaseInsensitiveSearch] |