stringByTrimmingCharactersInSet: is not removing c

2020-02-09 01:30发布

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?

6条回答
老娘就宠你
2楼-- · 2020-02-09 01:44

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:@""];
查看更多
成全新的幸福
3楼-- · 2020-02-09 01:46

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.

查看更多
男人必须洒脱
4楼-- · 2020-02-09 01:47

Use below

NSString * myString = @"A#BCD#D";
NSString * newString = [myString stringByReplacingOccurrencesOfString:@"#" withString:@""];
查看更多
放荡不羁爱自由
5楼-- · 2020-02-09 01:52

You could try

NSString *modifiedString = [yourString stringByReplacingOccurrencesOfString:@"#" withString:@""];
查看更多
仙女界的扛把子
6楼-- · 2020-02-09 02:00

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:@""];
}
查看更多
疯言疯语
7楼-- · 2020-02-09 02:08

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

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

Hope this helps.

查看更多
登录 后发表回答