objective-c 从 NSString 中删除字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/925780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove characters from NSString?
提问by Raju
NSString *myString = @"A B C D E F G";
I want to remove the spaces, so the new string would be "ABCDEFG".
我想删除空格,所以新字符串将是“ABCDEFG”。
回答by Tom Jefferys
You could use:
你可以使用:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:@" " withString:@""];
回答by Jim Dovey
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:@""];
回答by visakh7
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.
一个新字符串,其中接收器中所有出现的目标都被替换替换。
回答by Mitesh Khatri
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.
它将像 TRIM 方法一样工作。它将删除所有前后空格。
Thanks
谢谢
回答by justin
if the string is mutable, then you can transform it in place using this form:
如果字符串是mutable,那么您可以使用以下形式将其转换到位:
[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)];
回答by Kamleshwar
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.
希望这会帮助你。

