views:

456

answers:

2

Objective-C::

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

A: 

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

Wade Williams
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
+7  A: 
NSCharacterSet* charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@" \n"];
NSString* trimmedStr = [aStr stringByTrimmingCharactersInSet:charsToTrim];
Tom Dalling
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 <rdar://problem/7230868> ER: Need for -[NSMutableString trimCharactersInSet:]
Quinn Taylor