V2EX
   Tag:
 Code
Posted in iPhone on September 22nd, 2008 by Xin

Trimming leading and trail whitespace is common for data parsed from XML or JSON, however, there isn’t an equivalent method like PHP’s trim() in Objective-C, but with categories it’s easy to add functions to existing classes like NSString.

NSString+trim.m implements a class method + (NSString *)trim:(NSString *)original extends NSString to do the same thing as PHP’s trim(). Download the zip, drag NSString+trim.h and NSString+trim.m to your project and use it like this:

#import "NSString+trim.h"

NSString * trimmed = [NSString trim:whatever]; // whatever is NSString from XML or anything that needs to be trimmed

Download: NSString+trim.zip

It works on both iPhone and Mac.