Reputation: 781
I am trying to find when a string matches (case insensitively) a string in an array of strings and, in turn, get the index number. There is a good way to do this when case is the same. Alternatively, the code below is able to tell me whether a case-insensitive match exists. However, I can't get it to tell me the index when the match is case-insensitive.
Can anyone suggest a way to do this?
- (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
}
}
Upvotes: 0
Views: 626
Reputation: 385
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.
Hope it helps. Be aware, idx can be NSNotFound.
Upvotes: 3