// 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; } |