![](/img/trans.png)
[英]C program to accept a string input and print number of vowels and most repeated vowels in the string
[英]C program that splits string into tokens and counts vowels
我正在嘗試做一個C程序,將字符串拆分為記號,並對找到的每個單詞中的元音計數; 如果有兩個以上的元音,請顯示單詞。 那就是我試圖做的。 我認為strtok是獲取單詞的最簡單方法,但是我找不到元音並打印單詞。 該程序將不會打印任何內容。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[100], *r;
int i, contor,c;
printf("s = ");
gets(s);
r = strtok(s, " ");
while (r != NULL)
{
while(*r!='\0')
{
if (*r == 'a' || *r == 'A' || *r == 'e' ||
*r == 'E' || *r == 'i' || *r == 'I' ||
*r =='o' || *r=='O' || *r == 'u' || *r == 'U')
{
contor++;
}
r++;
}
if (contor>=2)
printf("%s \n",r);
r = strtok(NULL, " ");
}
return 0;
}
是的,因為在您調用printf
時r
已經指向了n終止字符(由於元音搜索循環)
您必須存儲指針才能打印單詞
const char *w = r;
while(*r!='\0')
{
if (*r == 'a' || *r == 'A' || *r == 'e' || *r == 'E' ||
*r == 'i' || *r == 'I' || *r =='o' || *r=='O' ||
*r == 'u' || *r == 'U')
{
contor++;
}
r++;
}
if (contor>=2)
printf("%s \n",w);
請注意,您的if
效率很低。 轉換為小寫字母和/或使用switch
/ case
語句將降低復雜性。
while(*r!='\0'){
switch (tolower(*r))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
contor++;
}
r++;
}
哦, 永遠不要使用gets
。 由於不安全,已將其從標准中刪除。 您可以使用scanf
有一個限制:
scanf("%99s",s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.