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] 
filteredArrayUsingPredicate:predicate];

    stringWithSpaces = [arrayOfWordsInTextView componentsJoinedByString:@" "];

Comments

Popular posts from this blog

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

payUmoney Payment Gateway Integration in iOS App (Objective C)

Check Internet Connectivity Using AFNetworking 2.0