views:

46

answers:

2

Hi friends..
I have a NSString(e.g. 'P1')
I have to add 1 in this NSString to get 'P2'. How will i do this??
Thanks for any help.

+3  A: 

Split it in to a prefix containing the P and a suffix containing the number. How you do this depends on the possible format of your string.

Then send intValue to the string.

Increment the number

Put it all back together with -stringWithFormat:

JeremyP
For the problem above, I think this would be the best and fastest solution. +1
hellozimi
If you want some code, see my answer, which does exactly what Jeremy states.
Joshua
A: 

You can convert your NSString to an NSInteger like so:

NSInteger myInteger = [[myString substringWithRange:NSMakeRange(1, 1)] integerValue];

In your case if myString was your string P1, myInteger would be 1. So you could then do:

myInteger = myInteger + 1;

Which would then make myInteger 2. To then put that number back after P do:

myString = [NSString stringWithFormat:@"P%i", myInteger];

Now myString is P2.

Joshua
Thanks a lot...