字串比較是日常開發裡最高頻的操作之一,但 Objective-C 提供的 API 比你想的多。以下用一段可直接執行的程式碼把常用方法一次跑過,並逐項說明差異。
NSString *str; // 以格式化方式產生字串 str = [NSString stringWithFormat:@"This is %@", @"John"]; NSLog(@"str--->%@", str); // 字串長度 NSLog(@"The length of this string is %@", [str length]);
BOOL isequal = [str isEqualToString:@"this is John"]; // 回傳 NO
這個方法是嚴格比對,區分大小寫,因此 "This is John" 與 "this is John" 不相等。實務上這是最常用、也最容易踩坑的一個——表單驗證、狀態判斷時若忘了大小寫差異,就會出現莫名的比對失敗。
int result = [@"bool" compare:@"cool"]; NSLog(@"The result is %d", result);
回傳值為 NSComparisonResult 列舉:
typedef enum _NSComparisonResult {
NSOrderedAscending = -1, // 前面的字串排在後面
NSOrderedSame = 0, // 兩者相等
NSOrderedDescending = 1 // 前面的字串排在後面
} NSComparisonResult;
注意它回傳的是「排序關係」而非布林值,因此適合用在排序的 comparator 中。
常用選項有三個,可以用位元或運算子組合:
int result1 = [@"This is John" compare:@"this is John"
options:NSCaseInsensitiveSearch | NSNumericSearch];
NSLog(@"The result is %d", result1); // 0,即 NSOrderedSame
所以「不區分大小寫的比較」正解就是這一條:compare:options: 搭配 NSCaseInsensitiveSearch。而 NSNumericSearch 在處理含編號的檔名、版本號時特別有用,能避免 "10" 排在 "2" 前面的反直覺結果。
BOOL isHas = [str hasPrefix:@"This"]; // YES BOOL isHas = [str hasSuffix:@"John"]; // YES
這兩個方法同樣區分大小寫。若要忽略大小寫,可改用 rangeOfString:options: 搭配 NSAnchoredSearch,或直接先把兩邊轉成同一大小寫再比。
NSRange range = [str rangeOfString:@"is" options:NSCaseInsensitiveSearch]; NSLog(@"The location of 'is' is %d", range.location);
找不到時 range.location 會是 NSNotFound,因此判斷「是否包含某子字串」的標準寫法是:
if ([str rangeOfString:@"keyword"].location != NSNotFound) {
// 包含
}
另外提醒一個 Swift 的對照:在 Swift 中這些操作已改名為 ==(完全相等)、caseInsensitiveCompare、hasPrefix/hasSuffix 與 range(of:),行為一致但回傳型別多為 Bool 或 Range,不再需要自己比對 NSNotFound 之外的列舉值。