0

キーワード配列と文字列の配列があります。

私は現在、キーワードを反復処理し、文字列配列にフィルターを使用して、キーワードがそこにあるかどうかを判断しています (何らかの形で)。

以下のコードは機能しますが、別の単語内にキーワード (またはキーワードと同じ文字) がある場合、フラグが立てられます。すなわち。ストリングリボンでbonを検索すると、リボンにフラグが立てられます。キーワードが文字列内の他の文字/単語に囲まれている可能性があるため、正確な比較はしたくありません。

それを検索して、空白または括弧で囲まれている場合にのみフラグを立てる方法はありますか? すなわち。別の単語の一部ではありません..

NSArray *paInc = [productIncludes valueForKey:pa];
// This is the array of keywords

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

for (id include in paInc){

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", include];
    NSArray *filteredArray = [stringArray filteredArrayUsingPredicate:predicate];
    // stringArray is the array containing the strings I want to search for these keywords

    for (NSString *ing in filteredArray){
        if ([ing length] > 0){
            if (![paMatchedIncludes containsObject:[NSString stringWithFormat:@"%@",ing]]){
                [paMatchedIncludes addObject:[NSString stringWithFormat:@"%@",ing]];
            }
        }
    }

}
4

2 に答える 2

1

次のコードで問題は解決しますか?

NSArray *paInc = @[@"bon",
                   @"ssib"];
// This is the array of keywords

NSArray *stringArray = @[@"Searching for bon in string ribbon would flag ribbon.",
                         @"I don't want to do an exact comparison as it's possible the keyword will be surrounded by other characters / words in the string."];
// stringArray is the array containing the strings I want to search for these keywords

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

for (id include in paInc){ // for every keyword
    for (NSString *nextString in stringArray) { // for every string
        NSArray *components = [nextString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ()"]];
        if ([components containsObject:include]) {
            [paMatchedIncludes addObject:nextString];
        }
    }
}

編集(コメントによる):大文字と小文字を区別しない比較の場合:

for (id include in paInc){ // for every keyword
    for (NSString *nextString in stringArray) { // for every string
        NSArray *components = [nextString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ()"]];
        for (NSString *nextComponent in components) {
            if([nextComponent caseInsensitiveCompare:include] == NSOrderedSame)
                [paMatchedIncludes addObject:nextString];
        }
    }
}
于 2013-09-20T08:16:34.047 に答える
0

正規表現が必要だと思います。

于 2013-09-20T07:28:50.800 に答える