0

For some odd reason, my stringByTrimmingCharacterInSet: allows the '%' through.

Why?

Simple code that demonstrates the issue (meant to extra a phone # from text):

    NSString * allowedSet = @"01234567890+-#";
    NSCharacterSet * disallowedSet =[[NSCharacterSet characterSetWithCharactersInString:allowedSet] invertedSet];

    in = @"+31%121212abc";
    out = [in  stringByTrimmingCharactersInSet:disallowedSet];

I would have expected as the output

... In  : +31%121212abc
... Out : +31121212

but I am getting:

... In  : +31%121212abc
... Out : +31%121212

Why is that? It seems to work for pretty much all other chars. Is the '%' special - or is this some odd URL related issue?

Pang
  • 9,564
  • 146
  • 81
  • 122
Dirk-Willem van Gulik
  • 7,566
  • 2
  • 35
  • 40
  • 1
    Trimming work only at the beginning and and the end of the string, no? – Larme Jun 04 '15 at 12:36
  • Aye - I realised that seconds after writing it - and answered my own question. – Dirk-Willem van Gulik Jun 04 '15 at 12:36
  • possible duplicate of [stringByTrimmingCharactersInSet: is not removing characters in the middle of the string](http://stackoverflow.com/questions/5581141/stringbytrimmingcharactersinset-is-not-removing-characters-in-the-middle-of-the) – Larme Jun 04 '15 at 12:37

1 Answers1

0

I am trimming the string; as opposed to replacing chars. So it ignores those not at the start or end; i.e. the chars in the middle of the string. Using stringByReplacingCharactersInSet: resolves this nicely.

@interface NSString (inefficientStringByRemovingCharactersInSet)
- (NSString *)stringByRemovingCharactersInSet:(NSCharacterSet *)characterSet;
@end

@implementation NSString (inefficientStringByRemovingCharactersInSet)
- (NSString *)stringByRemovingCharactersInSet:(NSCharacterSet *)characterSet {
    return [[self componentsSeparatedByCharactersInSet:characterSet]
       componentsJoinedByString:@""];
}
@end
Dirk-Willem van Gulik
  • 7,566
  • 2
  • 35
  • 40