1

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

我想检查调用的第二个 NSString 是否word包含 中的所有字符query或某些字符,但不包含 中未指定的其他字符query

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

请你能告诉我怎么做吗?

NSString *query = @"ABCDEFJAKSUSHFKLAFIE";
NSString *word  = @"fearing"; //would pass as NO as there is no 'n' in the query var.  
4

1 回答 1

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
    }
}
于 2012-10-29T03:02:10.403 回答