2017-04-24 1 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가 될 수 있음을 알아 두십시오.

관련 문제