你好我是iOS的新手,我试图循环我导入到Textview的txt文件,然后用“更好的词”替换“坏词”我有三个数组1持有转换的txt文件到一个数组。它们列出了它应该查找的坏词以及应该替换它们的好词列表。程序应该能够扫描文本并查找坏词,并根据坏词的值将其替换为更好的词。这是我到目前为止扫描文本时所拥有的。我正试图测试是否识别坏词,现在这不起作用。
- (IBAction)scanText:(id)sender
{
NSString *contents = [NSString stringWithContentsOfFile:textFile encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [contents componentsSeparatedByString:@" "];
NSArray *badword = [NSArray arrayWithObjects: @"Objectivity",@"people",nil];
NSArray *goodWord = [NSArray arrayWithObjects:@"Default", @"Creepers"];
for (NSString* bad in badword)
if ([lines containsObject: bad])
{
self.textView.text = [textFile stringByReplacingOccurrencesOfString:bad withString:@"##"];
}
}
答案 0 :(得分:1)
只需使用NSRegularExpression
即可。请注意,我还没有考虑过如何使用正则表达式,但这应该适用于大多数情况。
编辑:我错过了更换部分。这是替换:
NSString *string = @"This is a paragraph with bad words that we don't want!!";
NSArray *badwords = @[@"bad", @"words"];
NSArray *betterwords = @[@"good", @"something"];
NSMutableString *pattern = [NSMutableString stringWithString:@"([^A-Za-z]?)("];
NSString *pipe = @"";
for (NSString *badWord in badwords)
{
[pattern appendString:pipe];
[pattern appendString:badWord];
pipe = @"|";
}
[pattern appendString:@")([^A-Za-z]?)"];
NSMutableString *finalString = [string mutableCopy];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
[regex enumerateMatchesInString:string
options:0
range:NSMakeRange(0, string.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange badrange = [result rangeAtIndex:2];
NSString *badword = [string substringWithRange:badrange];
NSInteger index = [badwords indexOfObject:badword];
NSString *betterword = betterwords[index];
NSInteger offset = finalString.length - string.length;
badrange.location += offset;
[finalString replaceCharactersInRange:badrange withString:betterword];
}];
NSLog(@"%@", finalString);
结果:
2014-06-18 [71719:60b] This is a paragraph with good something that we don't want!!
无论如何,我并不是真的想解决正则表达式问题,而是如何解决这个问题的Objective-C问题。