I have an NSString *str, having value @"I like Programming and gaming.开发者_如何学C" 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?
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
NSString * newString = [@"I like Programming and gaming." stringByReplacingOccurrencesOfString:@"I" withString:@""];
newString = [newString stringByReplacingOccurrencesOfString:@"like" withString:@""];
newString = [newString stringByReplacingOccurrencesOfString:@"and" withString:@""];
NSLog(@"%@", newString);
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];
}
}
}
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];
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).
精彩评论