【发布时间】:2013-11-29 16:10:40
【问题描述】:
我有一个带有公开高分列表的游戏,我允许层输入他们的名称(或任何不超过 12 个字符的名称)。我正在尝试创建几个函数来从坏词列表中过滤掉坏词
我有一个文本文件。我有两种方法:
一个读入文本文件:
-(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*) 和我读到的列表:
-(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 似乎没有效果。我已经追踪到日志,所以我可以查看是否有单词通过并且它们是……除非我硬核到数组中,否则一行似乎看不到单词。
有什么建议吗?
【问题讨论】:
-
您的代码没有多大意义。您从 badWordsFilePath 中的文件加载 badWordFile,然后从 badWordsFile 中的文件加载坏词。然后用通过 componentsSeparatedByString 处理的 badWordsFile 覆盖该值(无论它是什么)。
-
但您的主要问题可能是未能从读取数组的元素中删除回车符(这可能是使用记事本创建的,或者添加回车符的东西)。尝试
stringByTrimmingCharactersInSet和whitespaceAndNewlineCharacterSet(在每个单词上)。 -
顺便说一句,这个计划充满了危险。许多完全合法的词在其中包含“坏”词。甚至(稍微)“坏”的词在不同的上下文中也完全可以:“新落雪胸前的月亮,给下面的物体带来正午的光泽”。
-
感谢 HOTLICKS 的建议 - 你能告诉我我对 XCODE 有点陌生吗?至于险恶的方案,我同意并欢迎更好的建议——我知道如果我不在那里设置任何保护措施,它就会被滥用。
-
HOTLICKS - 成功了!非常感谢!-
标签: objective-c file nsstring