NSString *theString =@" Hello this is a long string! ";
1. 去掉首尾的空字符
NSString *strResult = [theString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
3. 使用NSPredicate 筛选 去除 或者替换多余的
NSCharacterSet *whitespaces = [NSCharacterSetwhitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicatepredicateWithFormat:@"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];
// 1> 去除多余的 输出:Hello this is a long string!
// 2> theString = [filteredArray componentsJoinedByString:@""]; 完全去掉空格 输出:Hellothisisalongstring!
NSLog(@"%@", theString);