views:

357

answers:

3

Hi all,

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

Thanks for any help.

+2  A: 

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 ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
        i++;
    }
    return [self substringFromIndex:i];
}
@end
John Franklin
Thanks very much John, and everyone who helped. If I change the NSInteger line for 10.4 compatibility, it works just great. Cheers.
SirRatty
I forgot 10.4 doesn't have NSInteger. Most of my work targets mobile devices, so it's been a while since I did anything for Tiger. I'm glad it worked!
John Franklin
A: 

I didn't really have much time to test this, and I'm not sure if 10.4 contains the UTF8String method for NSString, but here's how I'd do it:

NSString+Trimming.h

#import <Foundation/Foundation.h>

@interface NSString (Trimming)

-(NSString *) stringByTrimmingWhitespaceFromFront;

@end

NSString+Trimming.m

#import "NSString+Trimming.h"

@implementation NSString (Trimming)

-(NSString *) stringByTrimmingWhitespaceFromFront
{
    const char *cStringValue = [self UTF8String];

    int i;
    for (i = 0; cStringValue[i] != '\0' && isspace(cStringValue[i]); i++);

    return [self substringFromIndex:i];
}

@end

It may not be the most efficient way of doing this but it should work.

helixed
+1  A: 

Here's what I would do, and it doesn't involve categories!

NSString* outputString = inputString;
NSRange range = [inputString rangeOfCharacterFromSet: [NSCharacterSet whitespaceCharacterSet]
    options: nil];
if (range.location == 0) 
    outputString = [inputString substringFromIndex: range.locatoin + range.length];

This is much less code.

lucius
It's only less code if you only want to trim white space in one place in your application.
JeremyP