如何从字符串中删除特定单词?

时间:2011-04-08 11:56:26

标签: iphone nsstring

我有一个NSString * str,有价值@“我喜欢编程和游戏。” 我必须删除“我”“喜欢”& “和”来自我的字符串所以它应该看起来像“编程游戏”

我怎么能这样做,任何想法?

5 个答案:

答案 0 :(得分:7)

NSString *newString = @"I like Programming and gaming.";
NSString *newString1 = [newString stringByReplacingOccurrencesOfString:@"I" withString:@""];
NSString *newString12 = [newString1 stringByReplacingOccurrencesOfString:@"like" withString:@""];
NSString *final = [newString12 stringByReplacingOccurrencesOfString:@"and" withString:@""];

分配给错误的字符串变量现在编辑好了

NSLog(@"%@",final);

输出:编程游戏

答案 1 :(得分:5)

NSString * newString = [@"I like Programming and gaming." stringByReplacingOccurrencesOfString:@"I" withString:@""];
newString = [newString stringByReplacingOccurrencesOfString:@"like" withString:@""];
newString = [newString stringByReplacingOccurrencesOfString:@"and" withString:@""];

NSLog(@"%@", newString);

答案 2 :(得分:4)

比一系列stringByReplacing...系列调用更高效,更易于维护:

NSSet* badWords = [NSSet setWithObjects:@"I", @"like", @"and", nil];
NSString* str = @"I like Programming and gaming.";
NSString* result = nil;
NSArray* parts = [str componentsSeparatedByString:@" "];
for (NSString* part in parts) {
    if (! [badWords containsObject: part]) {
        if (! result) {
            //initialize result
            result = part;
        }
        else {
            //append to the result
            result = [NSString stringWithFormat:@"%@ %@", result, part];
        }
    }
}

答案 3 :(得分:3)

这是一个老问题,但我想展示我的解决方案:

NSArray* badWords = @[@"the", @"in", @"and", @"&",@"by"];
NSMutableString* mString = [NSMutableString stringWithString:str];

for (NSString* string in badWords) {
     mString = [[mString stringByReplacingOccurrencesOfString:string withString:@""] mutableCopy];
}

return [NSString stringWithString:mString];

答案 4 :(得分:0)

创建字符串的可变副本(或将其初始化为NSMutableString),然后使用replaceOccurrencesOfString:withString:options:range:将给定字符串替换为@“”(空字符串)。