简体   繁体   English

从NSString中删除字符?

[英]Remove characters from NSString?

NSString *myString = @"A B C D E F G";

我想删除空格,所以新字符串将是“ABCDEFG”。

You could use: 你可以使用:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];

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:@""];

All above will works fine. 以上所有都可行。 But the right method is this: 但正确的方法是这样的:

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

It will work like a TRIM method. 它将像TRIM方法一样工作。 It will remove all front and back spaces. 它将删除所有前后空间。

Thanks 谢谢

Taken from NSString 取自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. 一个新字符串,其中接收器中所有出现的目标都被替换替换。

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)];

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. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM