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]
#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???)