19

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?

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
Sookcha
  • 217
  • 1
  • 2
  • 13
  • If you're looking for a one liner that can remove more than one character (you mentioned `NSCharacterSet`s, after all), see my answer: http://stackoverflow.com/a/26152034/901641 – ArtOfWarfare Oct 07 '14 at 12:04

6 Answers6

56

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.

Vladimir
  • 170,431
  • 36
  • 387
  • 313
18

You could try

NSString *modifiedString = [yourString stringByReplacingOccurrencesOfString:@"#" withString:@""];
visakh7
  • 26,380
  • 8
  • 55
  • 69
15

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:@""];
Pang
  • 9,564
  • 146
  • 81
  • 122
cescofry
  • 3,706
  • 3
  • 26
  • 22
  • +1, although I dislike the redundancy caused by using a `while` loop, so I wrote a method which uses recursion instead (`do-while` probably could have also removed the redundancies): http://stackoverflow.com/a/26152034/901641 – ArtOfWarfare Oct 01 '14 at 23:02
11

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:@""];
}
manecosta
  • 8,682
  • 3
  • 26
  • 39
ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
3

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

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

Hope this helps.

Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216
Rakesh Bhatt
  • 4,606
  • 3
  • 25
  • 38
2

Use below

NSString * myString = @"A#BCD#D";
NSString * newString = [myString stringByReplacingOccurrencesOfString:@"#" withString:@""];
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76