Cocoa - Trim all leading whitespace from NSString

SirRatty picture SirRatty · Jul 8, 2010 · Viewed 40.4k times · Source

(have searched, but not been able to find a simple solution to this one either here, or in Cocoa docs)

Q. How can I trim all leading whitespace only from an NSString? (i.e. leaving any other whitespace intact.)

Unfortunately, for my purposes, NSString's stringByTrimmingCharactersInSet method works on both leading and trailing.

Mac OS X 10.4 compatibility needed, manual GC.

Answer

John Franklin picture John Franklin · Jul 8, 2010

This creates an NSString category to do what you need. With this, you can call NSString *newString = [mystring stringByTrimmingLeadingWhitespace]; to get a copy minus leading whitespace. (Code is untested, may require some minor debugging.)

@interface NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace;
@end

@implementation NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace {
    NSInteger i = 0;

    while ((i < [self length])
           && [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
        i++;
    }
    return [self substringFromIndex:i];
}
@end