ปัญหา
วิธีเขียนโปรแกรม C นับจำนวนสระและพยัญชนะในสตริงที่กำหนด?
วิธีแก้
ตรรกะที่จะเขียนเพื่อนำไปใช้หาสระและพยัญชนะ:
if(str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U' || str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u')
หากเงื่อนไขนี้เป็นจริง ให้เพิ่มตัวนับสระ มิฉะนั้นเพิ่มตัวนับพยัญชนะ
ตัวอย่าง
โปรแกรม C นับจำนวนสระและพยัญชนะในสตริง:
/* Counting Vowels and Consonants in a String */
#include <stdio.h>
int main() {
char str[100];
int i, vowels, consonants;
i = vowels = consonants = 0;
printf("Enter any String\n : ");
gets(str);
while (str[i] != '\0') {
if(str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U' ||
str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') {
vowels++;
} else {
consonants++;
}
i++;
}
printf("vowels in this String = %d\n", vowels);
printf("consonants in this String = %d", consonants);
return 0;
}ผลลัพธ์
เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:
Enter any String: TutoriasPoint vowels in this String = 6 consonants in this String = 7