【问题标题】:convert a phrase to numbers in C将短语转换为C中的数字
【发布时间】:2013-12-01 12:43:18
【问题描述】:

如何将用户给出的短语转换为数字但不能使用 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);
}

但我有问题继续它

【问题讨论】:

  • 您可能需要了解计算机系统如何存储字符。一个好的起点是Wikipedia。还可以访问一些链接,以便您了解其他表示字符的方式以及它们可能会发生变化的原因。恕我直言,这听起来像是一个家庭作业,所以你真的应该做作业来找出原因。

标签: c arrays converters


【解决方案1】:

每个 char 基本上都是一个较小的 int。该值是来自ascii 图表的值,它对每个字母进行编码。如您所见,这些字母分为 2 个连续的块(一个用于大写,一个用于小写)。因此,为了使您的结果正确,您需要将所有字母转换为相同的大小写。您可以使用tolowertoupper 函数。 然后,您只需减去字母 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.
       }
   }

请注意,这只是一个指南,您需要添加我在上面解释的其他功能。在这种情况下,数值结果位于代码中。

【讨论】:

    【解决方案2】:

    首先,在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 仅包含大写字符)。

    【讨论】:

      猜你喜欢
      • 2014-05-20
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多