Tuesday, October 6, 2009

Category on NSString: lstrip and rstrip

I posted recently about a strip method for NSString. Since the method "trims" all occurrences of a given character, it is like Python's strip(). I thought it would be interesting to implement lstrip() and rstrip(). I did this as a category on NSString. Here is another NSString category that has more to do with Bioinformatics.

In the example, the app is built from the command line (with garbage collection), and all the code is in a single file. You will probably want to use XCode.

This is the output:


xyz 7
xyz 5
xyz 5


And here is the code:

// gcc -o test test.m -framework Foundation -fobjc-gc-only
// ./test
#import <Foundation/Foundation.h>

@interface NSString (Stripper)
-(NSString *) lstrip;
-(NSString *) rstrip;
@end

@implementation NSString(Stripper)
- (NSString *) lstrip {
int i, N;
unichar c;
N = [self length];
for (i = 0; i < N; i++) {
c = [self
characterAtIndex:i];
if (!(c == ' ')) { break; }
}
if (i == N) { return nil; }
return [self substringFromIndex:i];
}

- (NSString *) rstrip {
int i, N;
unichar c;
N = [self length];
for (i = N-1; i > -1; i--) {
c = [self
characterAtIndex:i];
if (!(c == ' ')) { break; }
}
if (i == -1) { return nil; }
return [self substringToIndex:i+1];
}
@end

int main (int argc, const char * argv[]) {
NSString *s = [NSString
stringWithString:@" xyz "];
NSLog(@"%@ %i", s, [s length]);
NSString *s2 = [s lstrip];
NSLog(@"%@ %i", s2, [s2 length]);
NSString *s3 = [s rstrip];
NSLog(@"%@ %i", s3, [s3 length]);
return 0;
}