stringByTrimmingCharactersInSet: is not removing characters in the middle of the string

♀尐吖头ヾ 提交于 2019-11-30 06:54:36

问题


I want to remove "#" from my string.

I have tried

 NSString *abc = [@"A#BCD#D" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"#"]];

But it still shows the string as "A#BCD#D"

What could be wrong?


回答1:


You could try

NSString *modifiedString = [yourString stringByReplacingOccurrencesOfString:@"#" withString:@""];



回答2:


stringByTrimmingCharactersInSet removes characters from the beginning and end of your string, not from any place in it

For your purpose use stringByReplacingOccurrencesOfString:withString: method as others pointed.




回答3:


I wrote a category of NSString for that:

- (NSString *)stringByReplaceCharacterSet:(NSCharacterSet *)characterset withString:(NSString *)string {
    NSString *result = self;
    NSRange range = [result rangeOfCharacterFromSet:characterset];

    while (range.location != NSNotFound) {
        result = [result stringByReplacingCharactersInRange:range withString:string];
        range = [result rangeOfCharacterFromSet:characterset];
    }
    return result;
}

You can use it like this:

NSCharacterSet *funnyCharset = [NSCharacterSet characterSetWithCharactersInString:@"#"];
NSString *newString = [string stringByReplaceCharacterSet:funnyCharset withString:@""];



回答4:


I previously had a relatively complicated recursive answer for this (see edit history of this answer if you'd like to see that answer), but then I found a pretty simple one liner: 

- (NSString *)stringByRemovingCharactersInSet:(NSCharacterSet *)characterSet {
    return [[self componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
}



回答5:


Refer to the Apple Documentation about: stringByReplacingOccurrencesOfString: method in NSString

NSString *str1=[str stringByReplacingOccurrencesOfString:@"#" withString:@""];

Hope this helps.




回答6:


Use below

NSString * myString = @"A#BCD#D";
NSString * newString = [myString stringByReplacingOccurrencesOfString:@"#" withString:@""];


来源:https://stackoverflow.com/questions/5581141/stringbytrimmingcharactersinset-is-not-removing-characters-in-the-middle-of-the

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