【问题标题】:How to save a char to an array in the position of its ascii num In c如何将char保存到其ascii数字位置的数组中
【发布时间】:2018-03-04 08:37:17
【问题描述】:

我正在研究凯撒密码,我正在尝试根据字母应该代表的 ascii 将我的密码密钥的字符保存在一个数组中。因此,如果我的密码字符密钥 [] = "codezyxwvutsrqpnmlkjihgfba" 数组 (c) 中的第一个字符应该代表字母 a,其 ascii 编号为 97。所以我想将 c 存储在数组中的第 97 个位置。每次我尝试这样做时,数组都是空的。

char key[] = {"codezyxwvutsrqpnmlkjihgfba"};

char alphabet[] = {"abcdefghijklmnopqrstuvwxyz"};

char answerKey[200] = "";

for (int i = 0; key[i] != '\0'; i++) {
    answerKey[(int) alphabet[i]] = key[i];
}

for (int i = 0; answerKey[i] != '\0'; i++) {
    printf("%c", answerKey[i]);
} 

【问题讨论】:

  • 题目的答案是a[c]=c;
  • 通过使用字母的 ASCII 码作为索引,您只为元素 97 到 122 赋值;所有其他元素都为零。因此,您的打印循环不起作用:answerKey[0] 为零。 (循环条件str[i] != '\0' 仅对没有嵌入空字符的字符串有用。)
  • 你应该缩小你的字母,比如(key[i]-97)%27)。通过这种方式,您可以将其存储在仅包含 27 个字母的数组中!

标签: c arrays char ascii


【解决方案1】:

在 C 中,您可以通过简单地进行强制转换将 char 转换为 int。

在内存中,当你有一个 char 'a' 时,值 97 被保存。当您使用 char 时,它只是您了解内存中写入内容的方式。您可以将此内存视为一个 int,并获取存储在那里的值。

例如:

char c = 'a';
printf("char is %c, int is %d", c, (int)(c));
// Output would be:
//   char is a, int is 97

如需更多信息,请阅读:How are different types stored in memory

【讨论】:

    【解决方案2】:

    您将在第一个元素处开始打印answerKey[] 数组,并告诉它在到达'\0' 时立即停止。我不相信answerKey[0] 不应该是'\0',因为所有可打印的ascii 字符都不是0。我希望你的answerKey[] 数组是空的,除了元素97-122 之间,所以如果你的密码将被使用仅适用于小写字母字符,可能只查看数组的那一部分。

    或者,您可以通过在放置元素地址时从元素地址中减去 'a' 来使您的 answerKey[] 数组仅容纳足够的空间来容纳您的密码。这样的事情可能会奏效:

    char answerKey[27] = "";
    
    for (int i = 0; key[i] !='\0'; i++) {
        answerKey[(int) alphabet[i] - 'a'] = key[i];
    }
    

    【讨论】:

      【解决方案3】:

      由于 answerkey 数组的值仅在 97 - 122 范围内(假设您只使用小写字母),因此数组的其他元素是垃圾。

      只需将 print for 循环更改为从 97 迭代到 122 即可获得所需的结果。

      char key[] = {"codezyxwvutsrqpnmlkjihgfba"};
      
      char alphabet[] = {"abcdefghijklmnopqrstuvwxyz"};
      
      char answerKey[200]="";
      
      for (int i = 0; key[i] != '\0'; i++) {
          printf("%c",alphabet[i]);
          answerKey[(int) alphabet[i]] = key[i];
          printf("%c",answerKey[(int)alphabet[i]]);
      }
      printf("\n");
      int i=0;
      for (i = 97;i<=122; i++) 
      {
          printf("%c", answerKey[i]);
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-31
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-14
        • 1970-01-01
        相关资源
        最近更新 更多