我正在尝试将字母转换为一串数字或整数。我可以这样做,但我想知道是否有更好的方法?我必须将 4 个字母转换为对应的数字,所以我用字母创建了一个 NSMutableArray,然后这样做是读取一个字符串,然后一次将字符串拉开。
编辑:所以如果我的消息是“MNOP”,我想要一个字符串是“13141516”
alphabetArray = [[NSMutableArray alloc] init];
[alphabetArray insertObject:@"0" atIndex:0];
[alphabetArray insertObject:@"A" atIndex:1];
[alphabetArray insertObject:@"B" atIndex:2];
[alphabetArray insertObject:@"C" atIndex:3];
[alphabetArray insertObject:@"D" atIndex:4];
[alphabetArray insertObject:@"E" atIndex:5];
[alphabetArray insertObject:@"F" atIndex:6];
[alphabetArray insertObject:@"G" atIndex:7];
[alphabetArray insertObject:@"H" atIndex:8];
[alphabetArray insertObject:@"I" atIndex:9];
[alphabetArray insertObject:@"J" atIndex:10];
[alphabetArray insertObject:@"K" atIndex:11];
[alphabetArray insertObject:@"L" atIndex:12];
[alphabetArray insertObject:@"M" atIndex:13];
[alphabetArray insertObject:@"N" atIndex:14];
[alphabetArray insertObject:@"O" atIndex:15];
[alphabetArray insertObject:@"P" atIndex:16];
[alphabetArray insertObject:@"Q" atIndex:17];
[alphabetArray insertObject:@"R" atIndex:18];
[alphabetArray insertObject:@"S" atIndex:19];
[alphabetArray insertObject:@"T" atIndex:20];
[alphabetArray insertObject:@"U" atIndex:21];
[alphabetArray insertObject:@"V" atIndex:22];
[alphabetArray insertObject:@"W" atIndex:23];
[alphabetArray insertObject:@"X" atIndex:24];
[alphabetArray insertObject:@"Y" atIndex:25];
[alphabetArray insertObject:@"Z" atIndex:26];
NSRange range1 = NSMakeRange(0, 1);
NSRange range2 = NSMakeRange(1, 1);
NSRange range3 = NSMakeRange(2, 1);
NSRange range4 = NSMakeRange(3, 1);
NSString *letter1 = [msg substringWithRange:range1];
NSString *letter2 = [msg substringWithRange:range2];
NSString *letter3 = [msg substringWithRange:range3];
NSString *letter4 = [msg substringWithRange:range4];
NSString *msgAsInt = [[NSString alloc]
initWithFormat:@"%d%d%d%d",
[alphabetArray indexOfObject:letter1 ],
[alphabetArray indexOfObject:letter2 ],
[alphabetArray indexOfObject:letter3 ],
[alphabetArray indexOfObject:letter4 ]];
任何建议都会很棒。我还没有测试过,但看起来还可以
谢谢,尼克