Remove whitespace from string in Objective-C

Crazer picture Crazer · Jan 10, 2011 · Viewed 81.7k times · Source

I have a couple of strings. Some have a whitespace in the beginning and some not. I want to check if a string begins with a whitespace and if so remove it.

Answer

Eimantas picture Eimantas · Jan 10, 2011

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]];