0

In Objective-C, how do you removed leading and trailing spaces from an occurrence of NSMutableString?

mensasnem
  • 33
  • 6
  • possible duplicate of [Collapse sequences of white space into a single character](http://stackoverflow.com/questions/758212/collapse-sequences-of-white-space-into-a-single-character) – Larme Jan 13 '15 at 15:59
  • 1
    @Larme I don't think that's quite a duplicate, as this is just about trimming, but hard to imagine there isn't a duplicate _somewhere_ – jrturton Jan 13 '15 at 16:06

2 Answers2

3

If string is a mutable string:

[string setString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
FD_
  • 12,947
  • 4
  • 35
  • 62
jrturton
  • 118,105
  • 32
  • 252
  • 268
1

You can use regular expression:

[string replaceOccurrencesOfString:@"(^\\s+)|(\\s+$)" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
Rob
  • 415,655
  • 72
  • 787
  • 1,044