Questions
Questions

Reputation: 20925

Remove characters from the beginning of an NSString

I have an NSString

NSString *data = @"abcdefghi";

but I want the data to be the "defghi"

What can I do to change it?

Upvotes: 1

Views: 5780

Answers (4)

Gauloises
Gauloises

Reputation: 2046

An alternative would be NSScanner if you don't know the exact location of your chars you want to delete: Apple Guide to NSScanners. You might want to look at the rest of the guide as well, as it very good describes what you can do with a string in Obj-C.

Upvotes: 1

Joshua
Joshua

Reputation: 15520

You could do :

NSMutableString *data = [NSMutableString stringWithString:@"abcdefghi"];
[data deleteCharactersInRange:NSMakeRange(0, 3)];

This is using NSMutableString which allows you to delete and add Characters/Strings to itself.

The method used here is deleteCharactersInRange this deletes the letters in the NSRange, in this case the range has a location of 0, so that it starts at the start, and a length of 3, so it deletes 3 letters in.

Upvotes: 4

Toastor
Toastor

Reputation: 8990

[data substringFromIndex:2]

this will return a new String with the characters up to the index (2) clipped.

Upvotes: 2

taskinoor
taskinoor

Reputation: 46037

NSString is immutable. You need to use NSMutableString unless you want to create a new string. Look at deleteCharactersInRange method.

Upvotes: 0

Related Questions