簡體   English   中英

將相等長度的字符串復制到新的字符串數組

[英]Copying strings of equal length to new string array

我有一個存儲在2D char數組中的單詞詞典。 我也將掃描的單詞存儲在結構中。 我試圖通過將長度等於掃描的單詞的單詞復制到單獨的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);
}
 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);
}

盡管未經測試,這應該可以工作。 正如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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM