检查NSString是否包含全部或部分字符

时间:2012-10-29 02:42:55

标签: objective-c ios nsstring comparison predicate

我有一个名为query的NSString,其中包含~10个字符。

我想查看第二个名为word的NSString是否包含query中的所有字符,或某些字符,但没有{{1}中未指定的其他字符}。

此外,如果查询中只出现一次字符,则该字词中只能出现一次该字符。

请告诉我怎么做?

query

1 个答案:

答案 0 :(得分:5)

以下是上半部分的答案:

NSCharacterSet *nonQueryChars = [[NSCharacterSet characterSetWithCharactersInString:[query lowercaseString]] invertedSet];
NSRange badCharRange = [[word lowercaseString] rangeOfCharacterFromSet:nonQueryChars];
if (badCharRange.location == NSNotFound) {
    // word only has characters in query
} else {
    // found unwanted characters in word
}

我需要考虑要求的后半部分。

好的,以下代码应满足这两个要求:

- (NSCountedSet *)wordLetters:(NSString *)text {
    NSCountedSet *res = [NSCountedSet set];

    for (NSUInteger i = 0; i < text.length; i++) {
        [res addObject:[text substringWithRange:NSMakeRange(i, 1)]];
    }

    return res;
}

- (void)checkWordAgainstQuery {
    NSString *query = @"ABCDEFJAKSUSHFKLAFIE";
    NSString *word  = @"fearing";

    NSCountedSet *queryLetters = [self wordLetters:[query lowercaseString]];
    NSCountedSet *wordLetters = [self wordLetters:[word lowercaseString]];
    BOOL ok = YES;
    for (NSString *wordLetter in wordLetters) {
        int wordCount = [wordLetters countForObject:wordLetter];
        // queryCount will be 0 if this word letter isn't in query
        int queryCount = [queryLetters countForObject:wordLetter];
        if (wordCount > queryCount) {
           ok = NO;
           break;
        }
    }

    if (ok) {
        // word matches against query
    } else {
        // word has extra letter or too many of a matching letter
    }
}