how to remove particular words from strings?

你。 提交于 2019-12-24 02:34:11

问题


I have an NSString *str, having value @"I like Programming and gaming." I have to remove "I" "like" & "and" from my string so it should look like as "Programming gaming"

How can I do this, any Idea?


回答1:


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:@""];

Assigned to wrong string variable edited now it is fine

NSLog(@"%@",final);

output : Programming gaming




回答2:


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

NSLog(@"%@", newString);



回答3:


More efficient and maintainable than doing a bunch of stringByReplacing... calls in series:

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



回答4:


It is an old question, but I'd like to show my solution:

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



回答5:


Make a mutable copy of your string (or initialize it as NSMutableString) and then use replaceOccurrencesOfString:withString:options:range: to replace a given string with @"" (empty string).



来源:https://stackoverflow.com/questions/5594694/how-to-remove-particular-words-from-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!