Remove whitespace from string in Objective-C

There is method for that in NSString class. Check stringByTrimmingCharactersInSet:(NSCharacterSet *)set. You should use [NSCharacterSet whitespaceCharacterSet] as parameter:

NSString *foo = @" untrimmed string ";
NSString *trimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

You could use the stringByTrimmingCharactersInSet NSString method with the whitespaceAndNewlineCharacterSet NSCharacterSet as such:

NSString *testString = @"  Eek! There are leading and trailing spaces  ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
                             [NSCharacterSet whitespaceAndNewlineCharacterSet]];

This will remove only the leading white space.

NSString *myString = @"   123   ";
NSLog(@"mystring %@, length %d",myString, myString.length);
NSRange range = [myString rangeOfString:@"^\\s*" options:NSRegularExpressionSearch];
myString = [myString stringByReplacingCharactersInRange:range withString:@""];
NSLog(@"mystring %@, length %d",myString, myString.length);

output

mystring    123   , length 9
mystring 123   , length 6