Replacing bad words in a string in Objective-C

£可爱£侵袭症+ 提交于 2019-12-20 01:10:34

问题


I have a game with a public highscore list where I allow layers to enter their name (or anything unto 12 characters). I am trying to create a couple of functions to filter out bad words from a list of bad words

I have in a text file. I have two methods:

One to read in the text file:

-(void) getTheBadWordsAndSaveForLater {

    badWordsFilePath = [[NSBundle mainBundle] pathForResource:@"badwords" ofType:@"txt"];
    badWordFile = [[NSString alloc] initWithContentsOfFile:badWordsFilePath encoding:NSUTF8StringEncoding error:nil];

    badwords =[[NSArray alloc] initWithContentsOfFile:badWordFile];
    badwords = [badWordFile componentsSeparatedByString:@"\n"];


    NSLog(@"Number Of Words Found in file: %i",[badwords count]);

    for (NSString* words in badwords) {

        NSLog(@"Word in Array----- %@",words);
    }


}

And one to check a word (NSString*) agains the list that I read in:

-(NSString *) removeBadWords :(NSString *) string {


    // If I hard code this line below, it works....
    // *****************************************************************************
    //badwords =[[NSMutableArray alloc] initWithObjects:@"shet",@"shat",@"shut",nil];
    // *****************************************************************************


    NSLog(@"checking: %@",string);

    for (NSString* words in badwords) {

       string = [string stringByReplacingOccurrencesOfString:words withString:@"-" options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];

        NSLog(@"Word in Array: %@",words);
    }

     NSLog(@"Cleaned Word Returned: %@",string);
    return string;
}

The issue I'm having is that when I hardcode the words into an array (see commented out above) then it works like a charm. But when I use the array I read in with the first method, it does't work - the stringByReplacingOccurrencesOfString:words does not seem to have an effect. I have traced out to the log so I can see if the words are coming thru and they are... That one line just doesn't seem to see the words unless I hardcore into the array.

Any suggestions?


回答1:


A couple of thoughts:

  1. You have two lines:

    badwords =[[NSArray alloc] initWithContentsOfFile:badWordFile];
    badwords = [badWordFile componentsSeparatedByString:@"\n"];
    

    There's no point in doing that initWithContentsOfFile if you're just going to replace it with the componentsSeparatedByString on the next line. Plus, initWithContentsOfFile assumes the file is a property list (plist), but the rest of your code clearly assumes it's a newline separated text file. Personally, I would have used the plist format (it obviates the need to trim the whitespace from the individual words), but you can use whichever you prefer. But use one or the other, but not both.

    If you're staying with the newline separated list of bad words, then just get rid of that line that says initWithContentsOfFile, you disregard the results of that, anyway. Thus:

    - (void)getTheBadWordsAndSaveForLater {
    
        // these should be local variables, so get rid of your instance variables of the same name
    
        NSString *badWordsFilePath = [[NSBundle mainBundle] pathForResource:@"badwords" ofType:@"txt"];
        NSString *badWordFile = [[NSString alloc] initWithContentsOfFile:badWordsFilePath encoding:NSUTF8StringEncoding error:nil];
    
        // calculate `badwords` solely from `componentsSeparatedByString`, not `initWithContentsOfFile`
    
        badwords = [badWordFile componentsSeparatedByString:@"\n"];
    
        // confirm what we got
    
        NSLog(@"Found %i words: %@", [badwords count], badwords);
    }
    
  2. You might want to look for whole word occurrences only, rather than just the presence of the bad word anywhere:

    - (NSString *) removeBadWords:(NSString *) string {
    
        NSLog(@"checking: %@ for occurrences of these bad words: %@", string, badwords);
    
        for (NSString* badword in badwords) {
            NSString *searchString = [NSString stringWithFormat:@"\\b%@\\b", badword];
            string = [string stringByReplacingOccurrencesOfString:searchString
                                                       withString:@"-"
                                                          options:NSCaseInsensitiveSearch | NSRegularExpressionSearch
                                                            range:NSMakeRange(0, string.length)];
        }
    
        NSLog(@"resulted in: %@", string);
    
        return string;
    }
    

    This uses a "regular expression" search, where \b stands for "a boundary between words". Thus, \bhell\b (or, because backslashes have to be quoted in a NSString literal, that's @"\\bhell\\b") will search for the word "hell" that is a separate word, but won't match "hello", for example.

  3. Note, above, I am also logging badwords to see if that variable was reset somehow. That's the only thing that would make sense given the symptoms you describe, namely that the loading of the bad words from the text file works but replace process fails. So examine badwords before you replace and make sure it's still set properly.



来源:https://stackoverflow.com/questions/20289672/replacing-bad-words-in-a-string-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!