XCode: NSString trim whitespace

If you e.g. work with the string of a NSTextfield an often needed to remove whitespaces and/or new line characters. The code below only removes whitespaces (U+0020) and tab character (U+0009).

NSString *string = @" my text with whitespaces ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

NSCharacterSet is a group of characters mostly used for search operations. If you like to remove whitespaces and new line characters code like this:

NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

There are a lot of more predefined Charactersets. For more Information see Apple Developer Reference.

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


comments powered by Disqus

Copyright Dunkel & Iwer GbR | Datenschutzerklärung | Impressum