NSRange非连续字符串搜索

时间:2015-07-12 06:41:57

标签: ios xcode nsrange

我的字符串是

NSString *str= @"Hello Hi How Are You Thank you";

如果我搜索“hi how”或“是你”或“谢谢”,我会使用NSCaseInsensitiveSearch获得结果。

NSRange r=[searchable rangeOfString:@"hi how" options:NSCaseInsensitiveSearch]

if(r.location!=NSNotFound)

NSLog(@"true");

但如果我搜索“hello how”或“hi you”。我没有得到任何结果。

NSRange r=[searchable rangeOfString:@"hi you" options:NSCaseInsensitiveSearch]

if(r.location!=NSNotFound)

NSLog(@"true");

请帮助我获得理想的结果。

由于

2 个答案:

答案 0 :(得分:1)

不确定这是否是你想要的

NSString *str= @"Hello Hi How Are You Thank you";

NSRange r1= [str rangeOfString:@"hi" options:NSCaseInsensitiveSearch];
NSRange r2 = [str rangeOfString:@"you" options:NSCaseInsensitiveSearch];
if(r1.location!=NSNotFound && r2.location!=NSNotFound && r2.location > r1.location)
{
    NSLog(@"true");
}

答案 1 :(得分:0)

你实际做的是“过滤”,而不是“排序”。在Swift中,您可以按如下方式实现所需的行为

var stringArray: [NSString] = ["a b c 2", "a d c 3", "a s d f c"]

let filterString = "a c"

stringArray.filter { (element) -> Bool in
    let filterComponents = filterString.componentsSeparatedByString(" ")
    for component in filterComponents {
        let range = element.rangeOfString(element as String, options: .CaseInsensitiveSearch)
        if range.location == NSNotFound {
            return false
        }
    }

    return true
}

print(stringArray)

将打印[a b c 2, a d c 3, a s d f c]

Objective-C中的等效代码段如下所示。

NSArray *stringArray = @[@"a b c 2", @"a d c 3", @"a s d f c"];

NSString *filterString = @"a c";
NSArray *filterComponents = [filterString componentsSeparatedByString:@" "];

NSMutableArray *filteredArray = [[NSMutableArray alloc] init];

for (NSString *string in stringArray) {
    bool matchesFilter = YES;

    for (NSString *component in filterComponents) {
        NSRange range = [string rangeOfString:component options:NSCaseInsensitiveSearch];
        if (range.location == NSNotFound) {
            // don't include in filteredArray
            matchesFilter = NO;
            break;
        }
    }

    if (matchesFilter) {
        [filteredArray addObject:string];
    }

}

NSLog(@"%@", filteredArray);

将打印( "a b c 2", "a d c 3", "a s d f c" )