Friday, 1 November 2013

Trim White Spaces from NSString

Once i was coding and got stuck over removing spaces from NSString.

To trim preceding, succeeding & white spaces in between  a NSString use below snippet:

    NSString *whitespaceString = @"      This   is  a        string   with       white      spaces         ";
  NSLog(@"String before trimming white spaces: %@", whitespaceString);
  whitespaceString = [whitespaceString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  while ([whitespaceString rangeOfString:@" "].location != NSNotFound)
  whitespaceString = [whitespaceString stringByReplacingOccurrencesOfString:@" " withString:@" "];
  NSLog(@"String after trimming white spaces: %@", whitespaceString);

OR - A better approach using NSPredicate

    NSString *stringWithSpaces = @"      this is    my text  with     lots  of          spaces which is bothering              me";
    NSCharacterSet *spaces = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
    NSArray *arrayOfWordsInTextView =           [[stringWithSpaces componentsSeparatedByCharactersInSet:spaces] 

    stringWithSpaces = [arrayOfWordsInTextView componentsJoinedByString:@" "];

No comments:

Post a Comment