您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

Objective-C 字串比較全攻略:區分大小寫、局部比對與搜尋選項

編輯:iOS 相關資訊

字串比較是日常開發裡最高頻的操作之一,但 Objective-C 提供的 API 比你想的多。以下用一段可直接執行的程式碼把常用方法一次跑過,並逐項說明差異。

NSString *str;

// 以格式化方式產生字串
str = [NSString stringWithFormat:@"This is %@", @"John"];
NSLog(@"str--->%@", str);

// 字串長度
NSLog(@"The length of this string is %@", [str length]);

一、isEqualToString: ——完全相同比對

BOOL isequal = [str isEqualToString:@"this is John"];   // 回傳 NO

這個方法是嚴格比對,區分大小寫,因此 "This is John" 與 "this is John" 不相等。實務上這是最常用、也最容易踩坑的一個——表單驗證、狀態判斷時若忘了大小寫差異,就會出現莫名的比對失敗。

二、compare: ——序列比較

int result = [@"bool" compare:@"cool"];
NSLog(@"The result is %d", result);

回傳值為 NSComparisonResult 列舉:

typedef enum _NSComparisonResult {
    NSOrderedAscending  = -1,   // 前面的字串排在後面
    NSOrderedSame       =  0,   // 兩者相等
    NSOrderedDescending =  1    // 前面的字串排在後面
} NSComparisonResult;

注意它回傳的是「排序關係」而非布林值,因此適合用在排序的 comparator 中。

三、compare:options: ——帶選項的比較

常用選項有三個,可以用位元或運算子組合:

  • NSLiteralSearch:完全逐字比對,區分大小寫
  • NSCaseInsensitiveSearch:忽略大小寫差異
  • NSNumericSearch:只比較字串的「數值大小」而非字面順序。例如 "file2" 會排在 "file10" 前面,而不是依字典序排在後面
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" 前面的反直覺結果。

四、hasPrefix: / hasSuffix: ——前後綴判斷

BOOL isHas = [str hasPrefix:@"This"];   // YES
BOOL isHas = [str hasSuffix:@"John"];   // YES

這兩個方法同樣區分大小寫。若要忽略大小寫,可改用 rangeOfString:options: 搭配 NSAnchoredSearch,或直接先把兩邊轉成同一大小寫再比。

五、rangeOfString:options: ——搜尋位置

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 之外的列舉值。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved