stringByTrimmingCharactersInSet
only removes characters from the beginning and the end of the string, not the ones in the middle.
1) If you need to remove only a given character (say the space character) from your string, use:
[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]
2) If you really need to remove a set of characters (namely not only the space character, but any whitespace character like space, tab, unbreakable space, etc), you could split your string using the whitespaceCharacterSet
then joining the words again in one string:
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 stringByReplacingOccurrencesOfString:withString:
. 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…