0

I am trying to remove the front character of a NSMutableString and have tried:

    [str setString: [str substringFromIndex:1]] ,
    [str deleteCharactersInRange:NSMakeRange(0,1)] 

and a few others. These two either remove every character or every character except for the one I am trying to remove so for example if I have the String "-2357" and am trying to remove the "-" then I get just the "-" when I should get "2357".

Am I doing something wrong, and how can I fix this?

ᗩИᎠЯƎᗩ
  • 2,122
  • 5
  • 29
  • 41

3 Answers3

3

If you want to use the deleteCharactersInRange method, do this

NSRange range = {0,1};
[str deleteCharactersInRange:range];

Or, you could use substringFromIndex like so:

str = [str substringFromIndex:1];


Contrary to what you are saying, [str deleteCharactersInRange:NSMakeRange(0,1)] should work fine, I don't know why that is not working.

[str substringToIndex:1] will return the string from the beginning to the index 1, which is -. What you want is substringFromIndex. And as this method returns a NSString, you will need to assign it to str; just calling the method on str is not enough.


Edit

Using the deleteCharactersInRange may pose problems for some type of characters. For more information refer to this a question here.

Instead, you can safely use

[str deleteCharactersInRange:[str rangeOfComposedCharacterSequenceAtIndex:0]]
Community
  • 1
  • 1
aksh1t
  • 5,410
  • 1
  • 37
  • 55
  • I have tried this, it removes all characters from my string and I am left with an empty String. – user3631142 May 13 '14 at 06:49
  • @user3631142, log the string both before and after. I bet it's not what you think it is. – Ken Thomases May 13 '14 at 06:51
  • @aksh1t, it's dangerous to remove characters by just assuming they're stand-alone and independent. I recommend `[str deleteCharactersInRange:[str rangeOfComposedCharacterSequenceAtIndex:0]]`. – Ken Thomases May 13 '14 at 06:53
  • @user3631142 I wish to disagree with you on this. Both of these methods are working perfectly fine. You should try logging the strings before and after like KenThomases suggests. – aksh1t May 13 '14 at 06:57
  • @Ken Thomases : Thank you for the pointer. I stand enlightened. :) I will edit my answer to update this. – aksh1t May 13 '14 at 06:58
2

instead of:

[str substringToIndex:1]

Do this:

[str substringFromIndex:1]
Hgeg
  • 545
  • 6
  • 19
1

If you want to remove first character of the string you can use this:-

string = [string substringFromIndex:1];
Kundan
  • 3,084
  • 2
  • 28
  • 65