简体   繁体   中英

How can I remove specific characters from an NSString programmatically?

I need help filtering NSStrings. Suppose I have a string called 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. Another time I might want to remove the two words "Hello hi" and the space after that so that only "World" is left.

Please can someone explain the basics of removing characters in NSStrings? I am totally new to the world of objective-c and reading the class-reference made me even more confused. I'm only 12 so don't be harsh on me for not understanding the class-reference.

For this case you need a 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). Now you´re on the "H"-character. 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. If this becomes a problem you can take a look at NSMutableString that have methods that manipulates the current string.

You cannot edit NSString object, it is immutable. You should use NSMutableString instead.

Xcode 9 • Swift 4 or later

These two methods to remove character from string:

dropLast() returns an optional, so it can be nil. removeLast() returns the last character, not optional, so it will crash if the string is empty.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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