views:

30

answers:

4

Hi, everyone,

I have a question about the objective-C. I have the following string

NSString *data = @"abcdefghi";

but I want the data to be the "defghi"

What can I do? Can anyone help me? Thank you.

A: 

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

taskinoor
+2  A: 
[data substringFromIndex:2]

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

Toastor
this will not delete the chars from that string, rather it will create a new string. though it is sufficient for many cases :-)
taskinoor
Also, `[data substringFromIndex:3]` is what the author wants, since the [documentation](http://developer.apple.com/mac/library/documentation/cocoa/reference/Foundation/Classes/NSString_Class/Reference/NSString.html#jumpTo_124) says that the given index is included in the result.
dreamlax
+1  A: 

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.

Joshua
You can't initialise an `NSMutableString` like that, you must use `[NSMutableString stringWithString:@"abcdefghi"]`.
dreamlax
Thanks, just realized that. Edited my question.
Joshua
+1  A: 

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.

Gauloises