Andreas Eriksson
Andreas Eriksson

Reputation: 9027

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.

Upvotes: 2

Views: 180

Answers (4)

wjl
wjl

Reputation: 7361

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');

Upvotes: 0

aViNaSh
aViNaSh

Reputation: 1328

int n=[@"123" intValue];

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

Upvotes: 1

christosc
christosc

Reputation: 1402

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.)

Upvotes: 0

edsko
edsko

Reputation: 1628

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

Upvotes: 7

Related Questions