tags:

views:

487

answers:

1

Hi all,

I'm doing a very simple trimming from a string. Basically it goes like this:

int main (int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *s = [[NSString alloc] initWithString:@"Some other string"];
    s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"%@",s);

    [pool drain];
    return 0;
}

No matter how many times I check, I can't find a mistake on the code. But the compiler keeps returning:

Running…
2009-12-30 08:49:22.086 Untitled[34904:a0f] Some other string

It doesn't trim the string at all. Is there a mistake in my code, because I can't believe something this simple doesn't work. Thanks!

Edit: I think I've figured my mistake. stringByTrimmingCharactersInSet only trims the string from the leftmost and rightmost ends of a string. Can anybody confirm this?

+1  A: 

You are correct - with your code stingByTrimmingCharactersInSet will trim the left and right whitespace but leave internal whitespace alone.

Note that there's also a memory leak in your code sample:

NSString *s = [[NSString alloc] initWithString:@"Some other string"];

This will leak when you re-assign to s in the next line.

dmercredi
Crap, thanks! I'm really still not used to this autorelease and release thingy..
ivg