从文本文件ios中搜索单词或单词组合

时间:2013-08-06 08:38:24

标签: ios search word combinations

我正在尝试使用此代码过滤单词

-(BOOL)isBadWord:(NSString*)string{

    NSString* path = [[NSBundle mainBundle] pathForResource:@"wordlist"
                                                 ofType:@"txt"];

    NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];

    NSString *delimiter = @"\n";
    NSArray *items = [content componentsSeparatedByString:delimiter];
    NSString *character = @" ";
    NSArray *searchItems = [string componentsSeparatedByString:character];

    BOOL isContain = false;

    for (int i = 0; i < searchItems.count; i++) {

        if (![[searchItems objectAtIndex:i] isEqual:@""]) {

            NSUInteger indexOfTheObject =[items containsObject:[searchItems objectAtIndex:i]];

            if (indexOfTheObject > 0) {
                isContain = true;
            }
        }
     }
    return isContain;
}

对于单个单词,这是好的,但如果文本文件中的单词组合不起作用。例如:     string = word1 {space} word2

1 个答案:

答案 0 :(得分:3)

您基本上需要做的是迭代一系列不良单词/组合,对于每个步骤,您应该在string上搜索此组合,如下所示:

BOOL isContain = NO;
for (NSString *badWord in items) {
    if ([string rangeOfString:badWord].location != NSNotFound) {
        isContain = YES;
        break;
    }
}
return isContain; 

请注意,BOOL可以是YESNO,但不是truefalse - 它是您应该在Objectve中使用的特殊标量类型-C使用Cocoa / CocoaTouch时。

干杯! :)

P.S。看起来你用字符串做了很多工作,看到this String Programming Guide's chapter by Apple可能对你有用。