s6luwJ0A3I
s6luwJ0A3I

Reputation: 1033

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.

Upvotes: 0

Views: 903

Answers (4)

Angi
Angi

Reputation: 67

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"

Upvotes: 0

Stefan Maier
Stefan Maier

Reputation: 78

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.

Upvotes: 1

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

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

Upvotes: 0

Daniel
Daniel

Reputation: 3881

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.

Upvotes: 0

Related Questions