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 o
A couple of thoughts:
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);
}
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.
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.