在Objective-C中替换字符串中的不良词 [英] Replacing bad words in a string in Objective-C

查看:63
本文介绍了在Objective-C中替换字符串中的不良词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有公开高分列表的游戏,可以在其中输入图层的名称(或不超过12个字符的任何数字).我正在尝试创建几个函数以从不良词列表中过滤出不良词

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);
    }


}

再检查一个单词(NSString*)会再次显示我阅读的列表:

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;
}

我遇到的问题是,当我将单词硬编码到数组中时(请参见上面的注释),然后它就像一个符咒一样工作.但是,当我使用通过第一种方法读取的数组时,它不起作用-stringByReplacingOccurrencesOfString:words似乎没有效果.我已经找到了日志,所以我可以看到这些单词是否正在通过,而它们却......除非我将其硬核到数组中,否则只有一行似乎看不到这些单词.

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.

有什么建议吗?

推荐答案

一些想法:

  1. 您有两行:

  1. You have two lines:

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

如果只想在下一行用componentsSeparatedByString替换initWithContentsOfFile,则没有必要这样做.另外,initWithContentsOfFile假定该文件是属性列表(plist),但是其余代码清楚地假定它是换行符分隔的文本文件.就个人而言,我会使用plist格式(它消除了从单个单词中修剪空格的需要),但是您可以使用任何喜欢的格式.但是请使用其中之一,但不能同时使用.

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.

如果您只停留在换行符分隔的坏词列表上,那么就摆脱掉initWithContentsOfFile所在的行,无论如何您都会忽略它的结果.因此:

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;
    }
    

    这使用正则表达式"搜索,其中\b表示单词之间的边界".因此,\bhell\b(或者,因为必须在NSString文字中加反斜杠,所以为@"\\bhell\\b")将搜索单词"hell",该单词是一个单独的单词,但与"hello"不匹配,例子.

    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.

    注意,在上面,我也在登录badwords,以查看该变量是否被重置.鉴于您所描述的症状,这是唯一有意义的事情,即从文本文件中加载坏词是可以的,但替换过程会失败.因此,在更换badwords之前,请先检查一下它,确保其设置正确.

    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.

    这篇关于在Objective-C中替换字符串中的不良词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆