[英]C program to accept a string input and print number of vowels and most repeated vowels in the string
我正在學習C,所以我正在做不同的C編程挑戰,其中之一就是該程序。 WAP接受用戶輸入的字符串並打印編號。 元音和字符串中最重復的元音。
我可以計算並打印元音的數量,但是我無法弄清楚應該如何計算字符串中重復次數最多的元音,盡管我可以直接在輸出屏幕上打印出來,而重復次數最多的元音只需打印即可內部循環中的vowels[i]
語句。 但是我想計算程序內部最重復的元音,然后有效地打印它。 我嘗試了不同的方法,但是沒有任何效果。 另外,我想使代碼小而高效。 有辦法嗎?
這是我到目前為止所做的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 150
int main()
{
char Statement[MAX];
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
int i, j;
puts("Enter a simple statement.");
fgets(Statement, 150, stdin);
printf("\nYou entered: %s\n", Statement);
for(i=0; i<=strlen(Statement); i++){
//Converting uppercase input to lowercase
Statement[i] = tolower((unsigned char)Statement[i]);
}
//Calling the function to print no. of
NumberOfVowels(Statement, vowels); vowels
return 0;
}
int NumberOfVowels(char Statement[], char vowels[])
{
int i, j, vowelsAmount = 0, count = 0;
for(i=0; i<5; i++){ //outer loop
for(j=0; j<=strlen(Statement); j++){ //inner loop
if(vowels[i] == Statement[j]){
vowelsAmount++;
printf("%c - ", vowels[i]);
}
}
}
printf("\nTotal number of vowels = %d", vowelsAmount);
return vowelsAmount;
}
您可以嘗試以下任何一種方法...
key
和value
作為成員的結構MAP
。 有幫助程序方法,可讓您使用key
如vowel
和value(否)填充MAP
結構。 occurrences
。 vowels
,列號表示。 occurrences
。 ascii
)的數組,並在每次出現時繼續將array[ascii(vowel)]
上的值增加1。 這是一種實現方式(我剛剛更新了您的代碼,所以它的內容很粗略,請努力使其看起來不錯並刪除多余的打印件)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 150
int NumberOfVowels(char Statement[], char vowels[], int counts[])
{
int i, j = 0;
for(j=0; j<strlen(Statement); j++) {
if (Statement[j] == '\0' || Statement[j] == '\n') {
continue;
}
for(i=0; i<5; i++) {
if(vowels[i] == Statement[j]) {
int ascii = (int) vowels[i];
counts[ascii] = counts[ascii] + 1;
}
}
}
for(i=0; i<5; i++) {
int ascii = (int) vowels[i];
printf("%c - %d ", vowels[i], counts[ascii]);
}
printf("\n");
return 0;
}
int main()
{
char Statement[MAX];
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
int counts[256] = {0};
int i, j;
puts("Enter a simple statement.");
fgets(Statement, 150, stdin);
printf("\nYou entered: %s\n", Statement);
for(i=0; i<=strlen(Statement); i++){
//Converting uppercase input to lowercase
Statement[i] = tolower((unsigned char)Statement[i]);
printf("%c ", Statement[i]);
}
//Calling the function to print no. of
NumberOfVowels(Statement, vowels, counts);
return 0;
}
樣品運行
You entered: Hello How are you, I am fine!
h e l l o h o w a r e y o u , i a m f i n e !
a - 2 e - 3 i - 2 o - 3 u - 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.