Ad

Our DNA is written in Swift
Jump

Remove Whitespace from NSString

In Cocoa Touch you always need to write more to achieve the same …

NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)

While such a standard task might look excessively much code to write, you gain many additional possibilites of what you could want to trim away. NSCharacterSet also knows these other sets. 

  • alphanumericCharacterSet
  • capitalizedLetterCharacterSet
  • controlCharacterSet
  • decimalDigitCharacterSet
  • decomposableCharacterSet
  • illegalCharacterSet
  • letterCharacterSet
  • lowercaseLetterCharacterSet
  • newlineCharacterSet
  • nonBaseCharacterSet
  • punctuationCharacterSet
  • symbolCharacterSet
  • uppercaseLetterCharacterSet
  • whitespaceAndNewlineCharacterSet
  • whitespaceCharacterSet

Categories: Recipes

6 Comments »

  1. Nice one 🙂
    Just when I needed it.

  2. You saved my day!

  3. This only removes whitespace from the beginning and end of a string. OmniFoundation (NSMutableString-OFExtensions) has a correct implementation that removes characters determined by a NSCharacterSet everywhere:
    https://github.com/omnigroup/OmniGroup/blob/master/Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSMutableString-OFExtensions.m