Remove all whitespaces from NSString

后端 未结 11 1824
北荒
北荒 2020-12-04 06:23

I\'ve been trying to get rid of the white spaces in an NSString, but none of the methods I\'ve tried worked.

I have \"this is a test\" and

11条回答
  •  清歌不尽
    2020-12-04 07:13

    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.

提交回复
热议问题