Search code examples
cocoansstringwhitespacetrim

Cocoa - Trim all leading whitespace from NSString


(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.


Solution

  • 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