字符串去掉空格问题

1.去掉两端空格:

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] ;

2.去掉所有空格:

[str stringByReplacingOccurrencesOfString:@" " withString:@""]  

3.去掉多余空格:

  1. NSString *str = @"    this     is a    test    .   ";  
  2.       
  3.     NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];  
  4.     NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];  
  5.       
  6.     NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces];  
  7.     NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];  
  8.     str = [filteredArray componentsJoinedByString:@" "];  
原文地址:https://www.cnblogs.com/paideblogs/p/5150705.html