2014-02-28 47 views
-2

我需要一种方法来检查[msg valueForKey:@"text"]是否包含currentString,如果是,它应该替换为字符*,具体取决于单词的长度。检查单词是否在字符串中,并替换字符串

我该怎么做?下面的代码是多远我来:

NSDictionary *msg = [self.messages objectAtIndex:indexPath.row]; 

for (NSString *currentString in badwords) 
{ 
    if ([[msg valueForKey:@"text"]]) { 

    } 
} 
+0

根据您调用数组“BADWORDS”,我假设你想创建一个淫秽的过滤器。试图过滤“坏字”是一场噩梦。你的方法和目前被接受的答案的方法,对于一个淫秽过滤器来说是非常天真的,并且会导致类似“阿特伍德在这里描述的”美国缺陷“和”肌肉车“的结果。 ](http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/) – NJones

+0

我明白了。那么接下来会是什么? – user3258468

+0

这可能是我去图书馆购物的罕见时间之一 - 或者至少浏览一些开放源代码库。如果你必须自己实现它,无论出于何种原因,请考虑让Apple的框架为你完成一些工作。例如,让'NSString'通过使用'enumerateSubstringsInRange:options:usingBlock:'并传递'NSStringEnumerationByWords'作为选项,然后检查传入块的子字符串是否在“badwords”数组中/组。当然这需要集合包含“坏字”的所有排列。 – NJones

回答

2

可以使用stringByReplacingOccurrencesOfString方法:

NSString *newString = [oldString stringByReplacingOccurrencesOfString:currentString 
                  withString:replacementString]; 

您可以创建替换字符串是这样的:

NSMutableString *replacementString = [[NSMutableString alloc] init]; 

for (int i = 0; i < currentString.length; i++) 
{ 
    [replacementString appendString:@"*"]; 
} 
0

你应该读取NSString类的引用。有一整套方法支持这种事情。针对您的特殊需要,看着像rangeOfString方法:或stringByReplacingOccurrencesOfString:withString:

0

如何:

NSDictionary *msg = [self.messages objectAtIndex:indexPath.row]; 
NSString *redactedString = [msg valueForKey:@"text"]; 
for (NSString *currentString in badwords) 
    redactedString = [redactedString stringByReplacingOccurrencesOfString:currentString 
                 withString:@"*"]; 
NSLog(redactedString); 

从@reecon改编。

相关问题