将相等长度的字符串复制到新字符串数组

时间:2015-11-10 19:22:07

标签: c arrays string

我有一个存储在2D字符数组中的单词字典。我还有一个存储在结构中的扫描字。我试图“瘦下来”。我的主要词典通过将长度等于扫描的单词的单词复制到单独的2D数组中。然后我想打印出新阵列。

即如果扫描的单词= hello,则所有相同长度的单词将被复制到新数组中。

我的代码只是无限地打印数组的第一个单词

words.startword是扫描的字词。

void get_equal_length (char equal_length_dictionary[MAX_WORDS][MAX_WORD_LENGTH], char dictionary[MAX_WORDS][MAX_WORD_LENGTH], Scanned_words words)

{
int i, word_count = 0;

for (i = 0; dictionary[i] != '\0'; i++)
    {
        if (strlen(*dictionary) == strlen(words.startword))
            {
                strcpy(*equal_length_dictionary, *dictionary);
                word_count++;
                printf("Word #%d: %s\n", word_count, *equal_length_dictionary);
            }
    }
    printf("Equal length words: %d\n", word_count);
}

2 个答案:

答案 0 :(得分:2)

for (i = 0; dictionary[i] != '\0'; i++)
{
    if (strlen(dictionary) == strlen(words.startword))
    {
       strcpy(*equal_length_dictionary, *dictionary);

应该是:

for (i = 0; dictionary[i][0] != '\0'; i++)
{
    if (strlen(dictionary[i]) == strlen(words.startword))
    {
      strcpy(equal_length_dictionary[i], dictionary[i]);

另外,为了提高速度,最好在循环之前只计算一次strlen(words.startword),而不是在每次迭代时在循环内重新计算它。您也不应忘记使用空字符串终止新数组。

完整的代码将是:

void get_equal_length(char equal_length_dictionary[MAX_WORDS][MAX_WORD_LENGTH], char dictionary[MAX_WORDS][MAX_WORD_LENGTH], Scanned_words words)
{
  int i, word_count = 0, len = strlen(words.startword);

  for (i = 0; dictionary[i][0] != '\0'; i++)
  {
    if (strlen(dictionary[i]) == len)
    {
      strcpy(equal_length_dictionary[i], dictionary[i]);
      word_count++;
      printf("Word #%d: %s\n", word_count, equal_length_dictionary[i]);
    }
  }
  // now we will also terminate the new array with a null string
  equal_length_dictionary[i][0] = '\0';
  printf("Equal length words: %d\n", word_count);
}

答案 1 :(得分:0)

这应该有效,尽管没有经过测试。正如Kevin在评论中提到的,你需要在循环中使用索引i。您还应该使用word_count作为索引:

void get_equal_length (char equal_length_dictionary[MAX_WORDS][MAX_WORD_LENGTH], char dictionary[MAX_WORDS][MAX_WORD_LENGTH], Scanned_words words)

{
int i, word_count = 0;

for (i = 0; i < MAX_WORDS; i++)
    {
        char* cur_word = dictionary[i];
        if (!cur_word || !*cur_word)
          break;
        if (strlen(cur_word) == strlen(words.startword))
            {
                strcpy(equal_length_dictionary[word_count], cur_word);
                word_count++;
                printf("Word #%d: %s\n", word_count, equal_length_dictionary[word_count]);
            }
    }
    printf("Equal length words: %d\n", word_count);
}