Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 436
Sookcha Avatar asked Apr 07 '11 12:04

Sookcha


4 Answers

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.

like image 61
Vladimir Avatar answered Nov 15 '22 00:11

Vladimir


You could try

NSString *modifiedString = [yourString stringByReplacingOccurrencesOfString:@"#" withString:@""];
like image 26
visakh7 Avatar answered Nov 15 '22 02:11

visakh7


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:@""];
like image 15
cescofry Avatar answered Nov 15 '22 02:11

cescofry


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:@""];
}
like image 11
ArtOfWarfare Avatar answered Nov 15 '22 01:11

ArtOfWarfare