如何将用户提供的短语转换为数字而不是ASCII表?例如,我有短语HELLO WORLD,我有一个数组,其中包含<>是0,A是1,B是2等,请帮忙!我的问题是我找不到比较两个数组的方法。 我已经开始了我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char text[]={' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','.',',',':','?'};
char number[125];
main(){
int i,j;
printf("Enter a message to encode:");
gets(number);
}
但我继续遇到问题
答案 0 :(得分:1)
每个char基本上都是一个较小的int。该值是ascii图表中对每个字母进行编码的值。如您所见,字母分为2个连续的块(一个用于大写,一个用于小写)。因此,为了使您的结果正确,您需要将所有字母转换为相同的大小写。您可以使用tolower或toupper功能。 然后,您只需要减去字母a的值,并对特殊字符执行一些检查。
你可以从这开始:
main(){
int i,j;
printf("Enter a message to encode:");
gets(number);
int codes[125];
for(int i = 0; i<strlen(number); i++){
codes[i] = toupper(number[i]) - 'A' + 1; // note that 'A' represents the code for letter A.
// +1 is because you want A to be 1.
}
}
请注意,这只是一个指南,您需要添加我上面解释的其他功能。在这种情况下,数值结果存在于代码中。
答案 1 :(得分:0)
首先,在text
:
char text[]={' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','.',',',':','?','\0'};
使用strchr
在文本中查找字符的位置。
for(int i = 0; i < strlen(number); i++){
int loc = (int)(strchr(text, number[i]) - &text[0]);
// save the loc in another array or do whatever you want.
}
您还应该确保number
中没有无效字符(输入中的'a'
无法正常工作,因为text
只包含大写字符)。