How to trim NSString in Objective C 2.0 – iOS, iPad, iPhone

When you want to trim a NSString in Objective C you can use NSString’s method stringByTrimmingCharactersInSet and passing it a [NSCharacterSet whitespaceAndNewlineCharacterSet] characterSet. This will trim your NSString from all newline and whitespace characters.

NSString *trimMe = @"    Trim this string      ";
trimMe = [trimMe stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"Trimmed String: ++%@++", trimMe);
//returnes Trimmed String: ++Trim this string+++

You can also trim just whitespace by passing [NSCharacterSet whitespaceCharacterSet] or trim just newline characters by passing [NSCharacterSet newlineCharacterSet]

About these ads

, , , , ,

  1. #1 by Guest on October 14, 2011 - 12:45 am

    What if I only wanted to remove the leading/trailing whitespace?

    (Why is everything in ObjC 100x harder than it needs to be???)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: