2017-04-24 68 views
0

我想查找一個字符串何時匹配(不區分大小寫)字符串數組中的字符串,然後獲取索引號。當案例相同時,有一個很好的方法可以做到這一點。或者,下面的代碼可以告訴我是否存在不區分大小寫的匹配。但是,當比賽不區分大小寫時,我無法讓它告訴我索引。IOS/Objective-C:獲取字符串數組中的字符串大小寫不區分大小寫

任何人都可以提出一種方法來做到這一點?

- (NSUInteger)findIndexOfWord:(NSString *)word inString:(NSString *)string { 
     NSArray *substrings = [string componentsSeparatedByString:@" "]; 

    if ([substrings indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){ 
    return (BOOL)([obj caseInsensitiveCompare:word] == NSOrderedSame); 
    }] != NSNotFound) { 
    // there's at least one object that matches term case-insensitively 
     int index = [substrings indexOfObject:word]; //if a case-insensitive match returns -1. 

     return index; // Will be NSNotFound if "word" not found 

    } 

} 

回答

1
NSString *word = @"YOLO"; 
NSArray<NSString *> *items = @[ @"hi", @"yolo", @"swag" ]; 

NSUInteger idx = [items indexOfObjectPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) { 
    return [obj caseInsensitiveCompare:word] == NSOrderedSame; 
}]; 

NSLog(@"%lu", (unsigned long)idx); 

indexOfObjectPassingTest:返回 陣列通過在給定塊中的測試中的第一個對象的索引。

希望它有幫助。請注意,idx可以是NSNotFound。

相關問題