【问题标题】:How to convert characters into integer in order to stock them in an array in C如何将字符转换为整数以便将它们存储在 C 中的数组中
【发布时间】:2021-08-13 04:17:26
【问题描述】:

我想根据每个单词中的第一个字母来存储从数组中的文本中获取的单词。 所有带有“a”的单词都将存放在第一种情况下,带有“b”的单词将存放在第二种情况下...... 我不知道如何将字符转换为索引以便将其存储在数组中。

例子:

T[26]

如果单词的第一个字母是'a',那么这个单词应该在第一种情况下被存储:

T[1]=单词。

为避免出现问题,我使用函数 strlwr 将文本转换为小写形式(小写),因此所有字符都根据 ASCII 码从 97 开始。

【问题讨论】:

  • 数组从索引 0 开始,因此 T[26] 的有效索引为 0-25。您可以通过从被测字母('a' - 'a' == 0'b' - 'a' == 1 等)中减去 'a' 来索引数组
  • @yanis 在 C 中的索引从 0 开始,而不是从 1 开始。
  • 所以我的工作是这样的:i=word[1]-'a' / T[i]=word /(word[i] 是单词中的第一个字符)/ 非常感谢兄弟
  • 你真的不需要转换任何东西。如果word 是您要放入数组的单词,您希望将单词推送到T[word[0] - 'a']。 (不清楚你将如何“储存”这些单词。T 是一个列表数组吗?)
  • 如果"apples""ants" 都是以'a' 开头的单词,你会怎么做?

标签: arrays c pointers char ascii


【解决方案1】:

听起来好像你想要一个单词列表数组,因为你有几个单词 以相同的字母开头。

struct word
{
  char* text;
  struct word* next;
}

struct word* words[26] = { NULL };

所以一旦你找到一个单词,就取它的第一个字符并将其转换为索引

int index = toupper(someword[0]) - 'A'; // 0..25  since A is ASCII 65

// check if there is any previous words
if (words[index] == NULL)
{
  // first word
  words[index] = malloc(struct word);
  words[index]->text = strdup(someword); // malloc,strcpy
  words[index]->next = NULL;
}
else // e.g. find last word
{
  struct word* last;
  struct word* p;
  
  for ( last = p = words[index]; p != NULL; p = p->next )
  {
    last = p;
  }
  
  assert(last == NULL); // must be at least one
  
  last->next = malloc(struct word);
  last->text = strdup(someword);
  last->next = NULL;
}

不,你需要一些函数来打印索引的所有单词

最后,您还需要清理所有分配的内存。

【讨论】:

  • 就是这样
【解决方案2】:

你需要一个单词数组。 你可以使用这样的语法来索引第一个数组:

   T['a']=word; //this works only if you have one word beginning with each letter
   T['a'][a_len]=word; //this is what you need to do if you want to have 
                       //an array of words for each letter

您可以使用它,因为“a”是一个 ASCII 字符,表示值为 97 的字符。但您必须确保 T 的内存分配到索引“z”。

【讨论】:

  • T['a'] 可能超出了T[26] 的范围。如果编码是 ASCII,正如您提到的,'a' 将是 97T 的最大索引是 25
  • 这个答案没有解释如何使用单词的第一个字符作为索引。
  • 其实数组是一个指针数组,数组的每个指针指向一个包含单词的链表,而我不知道该怎么做的事情是如何转换将单词的第一个字符转换为整数,表示数组中的大小写(0,1,2..etc)
  • @William Pursell 为您解答,您只需 T[word[0] - 'a']
  • 谢谢你们,我在第一条评论中尝试了解决方案,效果很好
猜你喜欢
  • 2012-09-29
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 2011-08-13
相关资源
最近更新 更多