简体   繁体   English

如何以编程方式从 NSString 中删除特定字符?

[英]How can I remove specific characters from an NSString programmatically?

I need help filtering NSStrings.我需要帮助过滤 NSStrings。 Suppose I have a string called myString.假设我有一个名为 myString 的字符串。

NSString *myString = @"HelloWorld";

How can I filter the word "Hello" out of it.我怎样才能过滤掉“你好”这个词。 Or how can I remove a specific amount of letters (Which it is beginning with) if I wanted to remove the first five letters.或者,如果我想删除前五个字母,如何删除特定数量的字母(以它开头)。

Another example of what I'm facing:我面临的另一个例子:

NSString *myString = @"Hello hi World"; 

Similarly, I want to remove "Hello" and the space after that.同样,我想删除“Hello”和之后的空格。 Another time I might want to remove the two words "Hello hi" and the space after that so that only "World" is left.另一次我可能想删除两个单词“Hello hi”及其后的空格,以便只留下“World”。

Please can someone explain the basics of removing characters in NSStrings?请有人解释在 NSStrings 中删除字符的基础知识吗? I am totally new to the world of objective-c and reading the class-reference made me even more confused.我对objective-c 的世界完全陌生,阅读类参考使我更加困惑。 I'm only 12 so don't be harsh on me for not understanding the class-reference.我只有 12 岁,所以不要因为我不理解类参考而对我苛刻。

For this case you need a NSMutableString:对于这种情况,您需要一个 NSMutableString:

NSMutableString *mutableString = @"Hello World";
[mutableString deleteCharactersInRange:NSMakeRange([mutableString length]-11, 6)];
NSLog (@"%@", mutableString);

Explanation for NSMakeRange: First you go to the end of the string and count back the length (11). NSMakeRange 的解释:首先你到字符串的末尾并计算长度(11)。 Now you´re on the "H"-character.现在你在“H”字符上。 Now you delete the following six characters.现在您删除以下六个字符。 "World" is now left over. “世界”现在已经结束了。

NSString have plenty of method to do almost everything, something to consider though is that NSString is immutable so all these methods returns a new string. NSString 有很多方法可以做几乎所有事情,但需要考虑的是 NSString 是不可变的,所以所有这些方法都返回一个新字符串。 If this becomes a problem you can take a look at NSMutableString that have methods that manipulates the current string.如果这成为一个问题,您可以查看 NSMutableString 具有操作当前字符串的方法。

You cannot edit NSString object, it is immutable.您不能编辑 NSString 对象,它是不可变的。 You should use NSMutableString instead.您应该改用 NSMutableString。

Xcode 9 • Swift 4 or later Xcode 9 • Swift 4 或更高版本

These two methods to remove character from string:从字符串中删除字符的这两种方法:

dropLast() returns an optional, so it can be nil. dropLast()返回一个可选项,因此它可以为零。 removeLast() returns the last character, not optional, so it will crash if the string is empty. removeLast()返回最后一个字符,不是可选的,因此如果字符串为空它会崩溃。

let string = "Hello World"

let substring1 = String(string.dropFirst())            // "ello World" 
let substring2 = String(string.dropFirst(2))           // "llo World" 

let substring3 = String(string.dropLast())             // "Hello Worl"
let substring4 = String(string.dropLast(2))            // "Hello Wor"

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

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