我对C很新,所以我想要一些建议。有没有更简单的方法来编写这个C代码?
此代码正在查看单词是anagrams还是no。代码威胁大写输入与小写输入相同,并且忽略输入字符不是字母。最后它应该和它显示的是单词anagrams或no。
我想知道有没有一种更简单的方法来编写这段代码,或者这是非常多的吗?
int alphabet[26] = {0}, sum = 0;
char first[20], second[20];
int i = 0;
printf("Enter the first word: ");
do
{
first[i] = getchar();
if(isalpha(first[i]))
alphabet[toupper(first[i]) - 'A'] += 1 ;
i++;
}while(first[i - 1] != '\n');
printf("Enter the second word: ");
i = 0;
do
{
second[i] = getchar();
if(isalpha(second[i]) && alphabet[toupper(second[i]) - 'A'] > 0)
{
alphabet[toupper(second[i]) - 'A'] -= 1;
}
i++;
}while(second[i - 1] != '\n');
for(i = 0; i <= 26 - 1; i++)
{
sum += alphabet[i];
}
if (sum == 0)
printf("Anagrams\n");
if (sum != 0)
printf("Not anagrams\n");
我没有一个编辑,在第二输入我拿出的,如果条件之一,现在它看起来像这样
do
{
second[i] = getchar();
if(isalpha(second[i]))
{
alphabet[toupper(second[i]) - 'A'] -= 1;
}
i++;
你应该张贴到[codereview.se。但是,这绝对可以简化。 – Quentin
第一个单词'abc',第二个单词'abcabc',会导致不正确的字谜匹配。在处理第二个单词时,如果任何字母的字母数为0,那么这些单词不是字谜。 – JS1
挑剔:C程序通常不是[* scripts *](http://en.wikipedia.org/wiki/Scripting_language)。 –