开发者

Problem with stringByTrimmingCharactersInSet:

开发者 https://www.devze.com 2022-12-15 06:45 出处:网络
I\'m doing a very simple trimming from a string. Basically it goes like this: int main (int argc, const char * argv[]) {

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 e开发者_开发技巧nds of a string. Can anybody confirm this?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消