去空格 whitespaceAndNewlineCharacterSet

本文转载至 http://blog.csdn.net/samuelltk/article/details/8994313 
1.去掉两端的空格
  1. [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]   

2.去掉多余的空格

  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:@" "];  

3.去掉所有空格

  1. [str stringByReplacingOccurrencesOfString:@" " withString:@""]  
原文地址:https://www.cnblogs.com/Camier-myNiuer/p/4498132.html