gpt4 book ai didi

IOS/objective-C : Get index of string in array of strings case-insensitive

转载 作者:行者123 更新时间:2023-11-28 19:31:41 24 4
gpt4 key购买 nike

我正在尝试查找字符串何时匹配(不区分大小写)字符串数组中的字符串,然后获取索引号。当大小写相同时,有一个很好的方法可以做到这一点。或者,下面的代码能够告诉我是否存在不区分大小写的匹配项。但是,当匹配不区分大小写时,我无法让它告诉我索引。

谁能推荐一种方法来做到这一点?

- (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。

关于IOS/objective-C : Get index of string in array of strings case-insensitive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com