簡體   English   中英

字謎的 C 程序如何(忽略大寫字母)

[英]C program for anagrams how to (ignore uppercase letters)

我的程序運行良好,這只是我需要的一個小建議; 首先這是我的代碼,用於檢查兩個單詞是否是字謎; 它工作正常;

#include <stdio.h>

int anagram_check(char [], char []);



int main()
{
   char word1[100], word2[100];
   int check;

   printf("Enter a Word\n");

   gets(word1);

   printf("Enter another word\n");
   gets(word2);




check = anagram_check(word1, word2);

   if (check == 1)

      printf("\"%s\" and \"%s\" are anagrams.\n", word1, word2);
   else

      printf("\"%s\" and \"%s\" are not anagrams.\n", word1, word2);

   return 0;
}

int anagram_check(char word1[], char word2[])
{
   int first[26] = {0}, second[26] = {0}, i = 0;

   while (word1[i] != 0)
   {
      first[word1[i]-'a']++;
      i++;
   }

   i = 0;

   while (word2[i] != 0)
   {
      second[word2[i]-'a']++;
      i++;
   }

   for (i = 0; i < 26; i++)
   {
      if (first[i] != second[i])
         return 0;
   }

   return 1;
}

現在我的問題是如何讓我的程序將大寫字母視為小寫字母? 例如。 當我輸入你好和你好時,它說這些詞不是字謎。 那么我該如何改變這一點。

還有它說“second[word2[i]-'a']++;” “a”代表什么/或做什么?

我還需要忽略任何不是字母的字符,我的程序是否已經是這種情況?

謝謝,任何幫助表示贊賞!

首先,從您的問題中刪除 c++ 標簽。 c 和 c++ 不一樣。 你在寫 C.

另外,如果您想知道為什么您的投票被低估並且人們有點苛刻,請讓我解釋一下。 這個網站通常對那些在沒有首先表明他們已經努力解決問題的情況下提出問題的人不友好。 我們並不是要刻薄 像這樣的問題被否決了,以阻止更多類似的問題出現。 我們不是來用勺子喂食的。

用勺子喂食

我建議編寫一個將字符轉換為小寫的小函數,然后在這些循環中調用它。 有 tolower 函數,但我認為編寫自己的函數是一個很好的練習。

while (word1[i] != 0)
{ 
   //you should call your function here
   first[word1[i]-'a']++;
   i++;
}
//....
while (word2[i] != 0)
{
   //you should call your function here.
   second[word2[i]-'a']++;
   i++;
}

我不會再具體了,因為這聽起來像是一個家庭作業問題。

“還有它所說的“second[word2[i]-'a']++;”'a'代表/或做什么?” 這里的“a”代表字母 a 的ascii 代碼 C 編譯器會將 'a' 視為常數 97。

您應該更仔細地考慮處理非字母數字字符時會發生什么。 我將在評論中與您討論。 提示:在這兩個循環之一中會發生一些不好的事情:

   while (word1[i] != 0)
   {
      first[word1[i]-'a']++;
      i++;
   }
   //...
   while (word2[i] != 0)
   {
      second[word2[i]-'a']++;
      i++;
   }

暫無
暫無

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

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