0

I am unsure how I can make each letter of the alphabet assigned to a number e.g. A = 1, B = 2 etc. So that when a user types say for example a name into the text field, the numerical values of all the letters are added up and given as a total.

This ultimately will then hopefully allow me to display a certain output based on the total of the letters.

Cheers, Leo

Curtis
  • 101,612
  • 66
  • 270
  • 352

2 Answers2

2

Easiest solution that comes to my mind, but it will only work as long as you assign incremental values based on the order of the alphabet letters.

// Make every letter uppercase to compare on the same scale of unicode values
NSString * str = [yourTextField.text uppercaseString];

NSUInteger total = 0;

for (int i = 0 ; i < str.length ; ++i ) {
    // 'A' unicode value is 65, so by substracting 64 you'll get 1 for A, 2 for B, 3 for C...
    total += [str characterAtIndex:i] - 64;
}

NSLog(@"Total is %d", total);

You should still make sure you don't get any symbols or so, but this will sum up all the letters in your string.

Ignacio Inglese
  • 2,605
  • 16
  • 18
0

Create an enum with all the letters. Then loop through the input string one character at a time, and add up the values.

enum  {
  A=1,
  B=2,
  C=3,
  // etc...
}; 
typedef int AlphabetIntCodes;

Then loop through using something like:

NSMutableString *textString = [[NSMutableString alloc] initWithString:txtText.text];
NSString *string = [NSMutableString stringWithFormat:@"%@",textString];

int stringLength = textString.length;
for (int i=0; i<stringLength; i++) {
    string = [string characterAtIndex:i];
        // Find the int value from the enum, and add it to a variable...
}

See looping through enum values to find the int values of each letter.

You don't have to use an enum, you could also just create a new AlphabetLetter NSObject class, and have two properties, the letter, and the int representation, and add them to an NSArray, and lookup the values of each letter through the array of AlphabetLetters.

Community
  • 1
  • 1
mservidio
  • 12,817
  • 9
  • 58
  • 84