In Objective-C, how do you removed leading and trailing spaces from an occurrence of NSMutableString?
Asked
Active
Viewed 713 times
0
-
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 Answers
3
If string
is a mutable string:
[string setString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
-
1Shouldn't `self` be `string`? This doesn't appear to be a category method. – rmaddy Jan 13 '15 at 18:02
-
-
Thank you. I found that exact same answer someplace else as well. As is probably obvious, I'm extremely new to Objective-C. – mensasnem Jan 14 '15 at 01:18
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
-
Thank you. GREP is a favorite of mine. But didn't know how to use it with mutable strings. – mensasnem Jan 14 '15 at 01:20