ปัญหา
เขียนโปรแกรมนับตัวอักษรที่ผู้ใช้ป้อน ว่าซ้ำกี่ครั้งในประโยค ใช้ strlen()
วิธีแก้ปัญหา
- รับประโยคจากผู้ใช้
printf("Enter a sentence\n"); gets(str); - รับตัวอักษรที่ต้องการนับ
printf("Enter a character to check how many times it is repeating\n"); scanf("%c", &c); - นับตัวอักษร
for(i=0; i
- พิมพ์ผลลัพธ์
ตัวอย่างโค้ด
#include <stdio.h>
#include <string.h>
int main() {
int i, count = 0;
char c, str[100];
printf("Enter a sentence\n");
gets(str);
printf("Enter a character to check how many times it is repeating\n");
scanf("%c", &c);
for(i = 0; i < strlen(str); i++) {
if(str[i] == c) {
count++;
}
}
printf("Letter %c repeated %d times\n", c, count);
return 0;
}ผลลัพธ์
Enter a sentence Here are the C Programming question and answers Enter a character to check how many times it is repeating n Letter n repeated 4 times