помогите улучшить код язык си
подскажите как можно написать этот код проще если такое возможно код работает как надо он берет ввод и считает каждую букву в алфавите и выводит на экран даже если буквы такой нет и он должен читать только маленькие буквы а большие и другие символы и даже пробелы он считает за другие символы количество которых он выводит в конце
int main() {
char ch[100];
int numberOfTimesAppeared = 0;
int numberOfOtherCharsAppeared = 0;
printf("Please enter your character set:\n");
gets(ch);
for (char letter = 'a'; letter != '{'; letter++) {
numberOfTimesAppeared = 0;
for (int i = 0; ch[i] != NULL; i++) {
if (letter == ch[i]) {
numberOfTimesAppeared++;
}
if (letter > 'a'){
continue;
}
if (!islower(ch[i]))
{
numberOfOtherCharsAppeared++;
}
}
printf(
"letter %c appeared %d time in the given set of characters\n",
letter, numberOfTimesAppeared
);
}
printf(
"number of other characters in the given set was: %d\n",
numberOfOtherCharsAppeared
);
}
Ответы (2 шт):
Автор решения: Harry
→ Ссылка
Ну... я бы делал так:
int main()
{
char cnt[26] = {0}, count = 0;
printf("Please enter your character set:\n");
for(int c = fgetc(stdin); c != '\n' && c != EOF; c = fgetc(stdin))
{
++count;
if (c >= 'a' && c <= 'z') cnt [c-'a']++;
}
for(int i = 0; i < 26; ++i)
{
printf("letter %c appeared %d time in the given set of characters\n",
'a'+i,cnt[i]);
count -= cnt[i];
}
printf("number of other characters in the given set was: %d\n",count);
}
Автор решения: iEPCBM
→ Ссылка
Можно создать массив, где будут храниться количества упоминаний символов. Тогда получится обойтись без вложенных циклов, что повысит производительность.
#include <stdio.h>
int main() {
char ch[100];
int numberOfOtherCharsAppeared = 0;
int chs['{'-'a'] = {0};
printf("Please enter your character set:\n");
gets(ch);
for (int i = 0; ch[i] != NULL; i++) {
if (ch[i]>='a' && ch[i]<'{') {
chs[ch[i]-'a']++;
} else {
numberOfOtherCharsAppeared++;
}
}
for (int i = 0; i<sizeof(chs)/sizeof(int); i++) {
printf(
"letter %c appeared %d time in the given set of characters\n",
(char)(i+'a'), chs[i]
);
}
printf(
"number of other characters in the given set was: %d\n",
numberOfOtherCharsAppeared
);
return 0;
}
