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