Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

นับจำนวนคำ สระ และความถี่ของตัวอักษรในสตริง

รับสตริง แล้วหาจำนวนคำทั้งหมด จำนวนสระ และความถี่ของตัวอักษรที่ผู้ใช้ระบุ

Input: enter a string: I love my MOM
       Enter a character to find frequency: M
Output:
Total frequency of M: 2
Total number of vowels: 4
Total number of words: 4

อัลกอริทึม

START
Step 1 Declare array of string, ch, i, freq=0, vow=0, word=0
Step 2 Input a string and a character ch
Step 3 Loop for from i to 0 and str[i]!='\0' and ++i
    Step 3.1 IF ch==str[i]
        Post incrementing freq
    Step 3.2 End If
    Step 3.3 IF str[i]=='a'||'e'||'i'||'o'||'u'||'A'||'E'||'I'||'O'||'U'
        Post incrementing vow
    Step 3.4 End If
    Step 3.5 IF str[i]==' '
        Post incrementing word
    Step 3.6 End If
Step 4 End For loop
STOP

ตัวอย่างโค้ด (C)

#include <stdio.h>

int main() {
    char str[1000], ch;
    int i, freq = 0, vow = 0, word = 0;
    printf("Enter a string of your choice: ");
    gets(str);
    printf("Enter a character of which you want to find the frequency: ");
    scanf("%c", &ch);
    for (i = 0; str[i] != '\0'; ++i) {
        if (ch == str[i])
            ++freq;
        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')
            ++vow;
        if (str[i] == ' ')
            word++;
    }
    printf("Frequency of %c = %d", ch, freq);
    printf("\ntotal number of vowels in a string are %d", vow);
    printf("\ntotal number of words in a string are %d", word + 1);
    return 0;
}

ผลลัพธ์

Enter a string of your choice: I love PrograMMIng
Enter a character of which you want to find the frequency: M
Frequency of M = 2
total number of vowels in a string are 6
total number of words in a string are 3