IOS/Objective-C: 获取不区分大小写的字符串数组中的字符串索引
IOS/Objective-C: Get index of string in array of strings case-insensitive
我正在尝试查找字符串何时匹配(不区分大小写)字符串数组中的字符串,然后获取索引号。当大小写相同时,有一个很好的方法可以做到这一点。或者,下面的代码能够告诉我是否存在不区分大小写的匹配项。但是,当匹配不区分大小写时,我无法让它告诉我索引。
任何人都可以建议一种方法吗?
- (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
}
}
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: Returns the index of the first object in the
array that passes a test in a given block.
希望对您有所帮助。请注意,idx 可以是 NSNotFound。
我正在尝试查找字符串何时匹配(不区分大小写)字符串数组中的字符串,然后获取索引号。当大小写相同时,有一个很好的方法可以做到这一点。或者,下面的代码能够告诉我是否存在不区分大小写的匹配项。但是,当匹配不区分大小写时,我无法让它告诉我索引。
任何人都可以建议一种方法吗?
- (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
}
}
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: Returns the index of the first object in the array that passes a test in a given block.
希望对您有所帮助。请注意,idx 可以是 NSNotFound。