【问题标题】:How to assign each letter in a textfield to a number in Xcode如何将文本字段中的每个字母分配给 Xcode 中的数字
【发布时间】:2012-01-03 21:44:41
【问题描述】:

我不确定如何将字母表中的每个字母分配给一个数字,例如A = 1, B = 2 等。因此,当用户在文本字段中输入例如名称时,所有字母的数值相加并作为总和给出。

这最终有望让我根据字母总数显示特定的输出。

干杯,狮子座

【问题讨论】:

  • 如果这是家庭作业,请将homework标签添加到您的问题中。

标签: objective-c ios variables


【解决方案1】:

我想到的最简单的解决方案,但它只有在您根据字母顺序分配增量值时才有效。

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

你仍然应该确保你没有得到任何符号左右,但这会总结你字符串中的所有字母。

【讨论】:

    【解决方案2】:

    创建一个包含所有字母的枚举。然后循环遍历输入字符串一次一个字符,并将值相加。

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

    然后循环使用类似的东西:

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

    请参阅looping through enum values 以查找每个字母的 int 值。

    你不必使用枚举,你也可以只创建一个新的 AlphabetLetter NSObject 类,并有两个属性,字母和 int 表示,并将它们添加到 NSArray,并查找每个的值字母通过 AlphabetLetters 数组。

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 1970-01-01
      • 2022-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2013-09-21
      • 1970-01-01
      • 2011-09-20
      相关资源
      最近更新 更多