I'm pretty new with C, so I wanted some advice.
This code is looking if the words are anagrams or no. The code threats upper-case input the same as lower-case and it ignores if the input character is not a letter. At the end it should and it does show are the words anagrams or no.
I was wondering is there an easier way to write this code or is this pretty much it?
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");
Aucun commentaire:
Enregistrer un commentaire