去空格

1.去掉两端的空格

  1. [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]   

2.去掉多余的空格

 
  1. NSString *str = @"    this     is a    test    .   ";  
  2.       
  3.     NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; //获取空格字符       
  4.     NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces];  
  5. //等同于NSArray *parts = [str componentsSeparatedByString:@" "];
  6.     NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];  
  7.     NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];  
  8.     str = [filteredArray componentsJoinedByString:@" "];  

3.去掉所有空格

    1. [str stringByReplacingOccurrencesOfString:@" " withString:@""]  
posted @ 2015-11-30 15:06  燕羽天空  Views(124)  Comments(0Edit  收藏  举报