stringByTrimmingCharactersInSet
只从字符串的开始和结束移除字符,而不是中间的字符.
1)如果只需要从字符串中删除给定字符(例如空格字符),请使用:
[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]
2)如果你真的需要删除一组字符(不仅是空格字符,还有空格、制表符、不可拆分空格等任何空格字符),你可以使用whitespaceCharacterSet
拆分字符串,然后将这些单词再次合并为一个字符串:
NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:@""];
Note that this last solution has the advantage of handling every whitespace character and not only spaces, but is a bit less efficient that the 100. So if you really only need to remove the space character and are sure you won't have any other whitespace character than the plain space char, use the first method.