1.去掉两端的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
//stringByTrimmingCharactersInSet: 是将字符串str和集合共同的部分,从str中剪掉。
2.去掉多余的空格
NSString *str = @" this is a test . ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; // 返回空格和tab
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
str = [filteredArray componentsJoinedByString:@" "];
// [NSCharacterSet whitespaceAndNewlineCharacterSet ]返回的是空格和tab和回车
结果:this空格is空格a空格test.
3.去掉所有空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""]