Thursday, September 24, 2009

Cocoa: strip for NSString

A few weeks ago I was complaining that NSString doesn't have a strip method like I use all the time in Python. I was wrong. It's called stringByTrimmingCharactersInSet:. Here is a bit of code (run from the command line) that exercises three useful NSString functions:

• componentsSeparatedByString
• componentsSeparatedByCharactersInSet
• stringByTrimmingCharactersInSet



// gcc -o strings stringstuff.m -framework Foundation
// ./strings
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *s = [[NSString alloc] initWithString:@"v\nx y;z"];
NSArray *a = [s componentsSeparatedByString:@"\n"];
NSLog(@"a = %@", [a description]);

NSCharacterSet *cs =
[NSCharacterSet characterSetWithCharactersInString:@"\n ;"];
a = [s componentsSeparatedByCharactersInSet:cs];
NSLog(@"a = %@", [a description]);

NSString *s2 = [[NSString alloc] initWithString:@" x y z "];
cs = [NSCharacterSet
characterSetWithCharactersInString:@" "];
NSString *s3 = [s2 stringByTrimmingCharactersInSet:cs];
NSLog(@"s3 = %@, length %u", [s3 description], [s3 length]);

[s release];
[s2 release];
[pool drain];
return 0;
}


Here is the output:

.. $ ./strings
.. s = v
x y;z
.. a = (
v,
"x y;z"
)
.. a = (
v,
x,
y,
z
)
.. s3 = x y z, length 5