去空格
1.去掉两端的空格
- [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
2.去掉多余的空格
- NSString *str = @" this is a test . ";
- NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; //获取空格字符
- NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces];
- //等同于NSArray *parts = [str componentsSeparatedByString:@" "];
- NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
- NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
- str = [filteredArray componentsJoinedByString:@" "];
3.去掉所有空格
- [str stringByReplacingOccurrencesOfString:@" " withString:@""]