Freeme
Freeme

Reputation: 19

How do I add a string of numbers in Objective-C

I'm trying to add all the numbers in a string in Objective-C and I couldn't figure it out.

For example:

NSString *number = @"234454875657";

How do you pull one number at a time and then add them up?

I know you have to use a loop and I tried to use the method name characterAtIndex: (NSUInteger)index but it returns unichar. Also, if the string is short, you can get the intValue and use % 10 and then divide 10 to add up all the digits, but what if it's a long string and only Double can hold it. % won't work on double values.

Upvotes: 0

Views: 152

Answers (3)

Nishith Shah
Nishith Shah

Reputation: 523

for(int i=0 < i < [str length]; i++) {
    NSString *char = [str characterFromIndex:[str length]-1];
}

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47729

Use a loop and characterAtIndex:. But what you get is a Unicode character, not a "number". You need to convert the character to a number somehow. There are a dozen ways to do this, but the simplest, if you know that the characters are all valid decimal digits, is to subtract '0' from the character value. Something like:

    int digit = (int)([number characterAtIndex:i] - (unichar)'0');

(This makes use of the knowledge that, in ASCII/Unicode, the decimal digits are sequential, in ascending order. A safe assumption unless you're using the Etruscan character set or some such.)

(But if you are doing this to, say, calculate the check code for a credit card number, you should play it safe and bounds-check the character somehow.)

Upvotes: 0

Caleb
Caleb

Reputation: 124997

One way would be to use NSString's -substringWithRange: method to pull substrings with length 1 out of the original string. You can then use NSString's -intValue to get the value of each substring.

Another way, if the string isn't too long, would be to convert the string to an integer first, and then add up the digits. It'd be something like this:

int sum = 0;
for (long long number = [@"234454875657" longLongValue]; number > 0; number /= 10) {
    sum += number % 10;
}

Upvotes: 1

Related Questions