Getting numbers from a string in iPhone programming

I have a string. It's always 3 letters long, and it can be counted on to only contain three integers. Say it looks like this:

NSString * numberString = @"123";

Now, I want to extract those numbers from it. 1, 2 and 3. In any other language I'd just fetch the character for each position and parse it, or even cast it.

However, Objective-C doesn't seem to have that. I found some other answer recommending that i use the characterAtIndex method, use numberWithChar on that, and then subtract the number "48" from it, leaving even myself scratching my head at the apparent stupidity of it all.

Is there no other, more elegant way to do this?

I tried using substringWithRange, but apparently there's no method for creating an NSRange, and it's incompatible with CFRangeMake for some reason.


How about [[numberString substringWithRange:NSMakeRange(0,1)] intValue]?

int n=[@"123" intValue];

From this you can get the individual numbers by n/100, n/10 and n%10.

How about this?

NSString * numberString = @"123";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString:numberString];
int n = [number intValue];

(Don't forget to release the formatter after you finish your conversions.)

NSString *numberString = @"123";
int firstDigit  = [numberString characterAtIndex:0] - '0';
int secondDigit = [numberString characterAtIndex:1] - '0';
int thirdDigit  = [numberString characterAtIndex:2] - '0';
NSLog(@"Your digits are %d, %d, %d", firstDigit, secondDigit, thirdDigit);

If you want to cheat:

char *numberString = [@"123" cStringUsingEncoding:NSASCIIStringEncoding];
printf(@"Your digits are %d, %d, %d\n", numberString[0] - '0',
                                        numberString[1] - '0',
                                        numberString[2] - '0');

Need Your Help

Runtime.exec doesn't do anything... (no errors)

java batch-file compilation runtime

I am trying to use java to run a batch file at an absolute location. The batch file will compile a couple of java files.

Textbox does not refreshed text, however messagebox does

c# .net multithreading string invoke

I am using two threads in this application which is a Tron game. I have a TextBox that displays the score at the end of each game. Each "game" is drawn in the 2nd drawThread Thread.