Remove characters from NSString?

后端 未结 6 1843
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 18:01
NSString *myString = @\"A B C D E F G\";

I want to remove the spaces, so the new string would be \"ABCDEFG\".

相关标签:
6条回答
  • 2020-11-29 18:14

    All above will works fine. But the right method is this:

    yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    

    It will work like a TRIM method. It will remove all front and back spaces.

    Thanks

    0 讨论(0)
  • 2020-11-29 18:16

    You can try this

    - (NSString *)stripRemoveSpaceFrom:(NSString *)str {
        while ([str rangeOfString:@"  "].location != NSNotFound) {
            str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
        }
        return str;
    }
    

    Hope this will help you out.

    0 讨论(0)
  • 2020-11-29 18:33

    if the string is mutable, then you can transform it in place using this form:

    [string replaceOccurrencesOfString:@" "
                            withString:@""
                               options:0
                                 range:NSMakeRange(0, string.length)];
    

    this is also useful if you would like the result to be a mutable instance of an input string:

    NSMutableString * string = [concreteString mutableCopy];
    [string replaceOccurrencesOfString:@" "
                            withString:@""
                               options:0
                                 range:NSMakeRange(0, string.length)];
    
    0 讨论(0)
  • 2020-11-29 18:34

    Taken from NSString

    stringByReplacingOccurrencesOfString:withString:
    

    Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

    - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
    

    Parameters

    target

    The string to replace.
    

    replacement

    The string with which to replace target.
    

    Return Value

    A new string in which all occurrences of target in the receiver are replaced by replacement.

    0 讨论(0)
  • 2020-11-29 18:36

    If you want to support more than one space at a time, or support any whitespace, you can do this:

    NSString* noSpaces =
        [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                               componentsJoinedByString:@""];
    
    0 讨论(0)
  • 2020-11-29 18:39

    You could use:

    NSString *stringWithoutSpaces = [myString 
       stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    0 讨论(0)
提交回复
热议问题