4

How do I trim " " and "\n" in NSMutableString?

apaderno
  • 28,547
  • 16
  • 75
  • 90
marcy
  • 4,213
  • 3
  • 23
  • 14

4 Answers4

12
NSCharacterSet* charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@" \n"];
NSString* trimmedStr = [aStr stringByTrimmingCharactersInSet:charsToTrim];
Tom Dalling
  • 23,305
  • 6
  • 62
  • 80
  • This is a good approach. It returns an immutable string, but there's really not a good alternative. Also see http://stackoverflow.com/questions/1422369/ and file a duplicate of ER: Need for -[NSMutableString trimCharactersInSet:] – Quinn Taylor Nov 21 '09 at 07:35
1

I know that this is an old question, but yes, it is possible to trim a mutable string without the need to return a new string. You just need a regular expression, an example below:

NSMutableString *mutable = [NSMutableString stringWithString:@" String to trim    \n"];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\n|  | $|^ " options:0 error:nil];
[regex replaceMatchesInString:mutable options:0 range:NSMakeRange(0, [mutable length]) withTemplate:@""];
ggrana
  • 2,335
  • 2
  • 21
  • 31
0

How about calling replaceOccurrencesOfString:withString:options:range twice, replacing " " and then "\n" with nothing?

wadesworld
  • 13,535
  • 14
  • 60
  • 93
  • This will work, but unless you specify the range, it less efficient than one would hope, since it will search the entire string for these characters (twice) rather than just the ends until all such characters have been removed. It also doesn't scale well to N characters — that's why we have NSCharacterSet. :-) – Quinn Taylor Nov 21 '09 at 07:38
0
NSString *trimmed = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
theDuncs
  • 4,649
  • 4
  • 39
  • 63