2014-12-30 63 views
0

我对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++; 
+1

你应该张贴到[codereview.se。但是,这绝对可以简化。 – Quentin

+2

第一个单词'abc',第二个单词'abcabc',会导致不正确的字谜匹配。在处理第二个单词时,如果任何字母的字母数为0,那么这些单词不是字谜。 – JS1

+5

挑剔:C程序通常不是[* scripts *](http://en.wikipedia.org/wiki/Scripting_language)。 –

回答

3

您的代码是不正确的:它认为“a”和“ ac“作为anagrams,由于错误的计数逻辑。我固定的,并有利于存储只是最近输入字符去掉整个firstsecond词的存储:

#include <stdio.h> 
#include <ctype.h> 

int main(void) 
{ 
    int alphabet[26] = {0}; 
    int ch; 
    int i; 

    printf("Enter the first word: "); 
    do 
    { 
    ch = getchar(); 
    if(isalpha(ch)) 
     alphabet[toupper(ch) - 'A']++; 
    }while(ch != '\n'); 

    printf("Enter the second word: "); 
    do 
    { 
    ch = getchar(); 
    if(isalpha(ch)) 
     alphabet[toupper(ch) - 'A']--; 
    }while(ch != '\n'); 

    for(i = 0; i < 26; i++) 
    { 
    if (alphabet[i]) 
    { 
     printf("Not anagrams\n"); 
     return 0; 
    } 
    } 

    printf("Anagrams\n"); 
    return 0; 
} 
+0

谢谢,我修复了这个错误。如果我在某些时候应该打印它们,我有用于这些文字的数组。 – TacoCat

+0

它似乎忽略了一个非alpha字符的输入。我怀疑这不是正确的行动。如果输入非alpha字符,则退出当前while循环 – user3629249

相关问题