我正在制作一个iOS应用程序,需要找出一个NSString
是否包含在一个NSArray
中的任何一个NSString
中。
我正在制作一个iOS应用程序,需要找出一个NSString
是否包含在一个NSArray
中的任何一个NSString
中。
BOOL found=NO;
for (NSString *s in arrayOfStrings)
{
if ([stringToSearchWithin rangeOfString:s].location != NSNotFound) {
found = YES;
break;
}
}
对于你的使用情况,这可能是一个愚蠢的优化,但取决于你正在迭代的数组大小,使用NSArray
的indexOfObjectWithOptions:passingTest:
方法可能是有帮助/更高效的。
使用这个方法时,您需要传递一些选项和包含您的测试的块。传递NSEnumerationConcurrent
选项将允许在多个线程上同时评估您的块并潜在地加速事物。我重新使用了invariant的测试,但使用了略微不同的方式。该块函数式地返回一个BOOL,类似于invariant的实现中的“found”变量。 “*stop = YES;”行表示迭代应该停止。
有关更多信息,请参阅NSArray参考文档。 参考文献
NSArray *arrayOfStrings = ...;
NSString *stringToSearchWithin = @"...";
NSUInteger index = [arrayOfStrings indexOfObjectWithOptions:NSEnumerationConcurrent
passingTest:^(id obj, NSUInteger idx, BOOL *stop)
{
NSString *s = (NSString *)obj;
if ([stringToSearchWithin rangeOfString:s].location != NSNotFound) {
*stop = YES;
return YES;
}
return NO;
}];
if (arrayOfStrings == nil || index == NSNotFound)
{
NSLog(@"The string does not contain any of the strings from the arrayOfStrings");
return;
}
NSLog(@"The string contains '%@' from the arrayOfStrings", [arrayOfStrings objectAtIndex:index]);
对Adam的答案进行微小的安全改进:使用"objectAtIndex:"会存在一个很大的问题,因为它完全不是线程安全的,会导致你的应用程序经常崩溃。所以我做了以下修改:
NSArray *arrayOfStrings = ...;
NSString *stringToSearchWithin = ...";
__block NSString *result = nil;
[arrayOfStrings indexOfObjectWithOptions:NSEnumerationConcurrent
passingTest:^(NSString *obj, NSUInteger idx, BOOL *stop)
{
if ([stringToSearchWithin rangeOfString:obj].location != NSNotFound)
{
result = obj;
*stop = YES;
//return YES;
}
return NO;
}];
if (!result)
NSLog(@"The string does not contain any of the strings from the arrayOfStrings");
else
NSLog(@"The string contains '%@' from the arrayOfStrings", result);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", theArray];
BOOL result = [predicate evaluateWithObject:theString];
BOOL found = NO;
NSString *string = @"ToSearchFor";
for (NSString *s in arrayOfStrings){
if ([string localizedCaseInsensitiveContainsString:s]) {
found = YES;
break;
}
}