在本教程中,我们将编写一个 C 程序,使用指针计算给定字符串中的元音和辅音。
使用指针计算字符串中的元音和辅音的程序
在下面的程序中,我们声明了一个char数组str来保存输入字符串,我们使用fgets()函数将其存储在数组中。我们已经将数组的基址(第一个元素的地址)赋给指针p。我们在while循环中使用指针p浏览输入字符串的所有字符,并在每次迭代时递增指针值。
#include <stdio.h>int main(){char str[100];char *p;int vCount=0,cCount=0;printf("Enter any string: ");fgets(str, 100, stdin);//assign base address of char array to pointerp=str;//'\0' signifies end of the stringwhile(*p!='\0'){if(*p=='A' ||*p=='E' ||*p=='I' ||*p=='O' ||*p=='U'||*p=='a' ||*p=='e' ||*p=='i' ||*p=='o' ||*p=='u')vCount++;elsecCount++;//increase the pointer, to point next characterp++;}printf("Number of Vowels in String: %d\n",vCount);printf("Number of Consonants in String: %d",cCount);return 0;}
输出:

