📜  C++程序使用Pointer计算字符串的元音

📅  最后修改于: 2021-05-30 09:35:01             🧑  作者: Mango

先决条件: C++中的指针

给定字符串小写英文字母。任务是使用指针计算字符串存在的元音数量

例子:

Input : str = "geeks"
Output : 2

Input : str = "geeksforgeeks"
Output : 5 

方法:

  1. 使用字符数组初始化字符串。
  2. 创建一个字符指针,并使用字符数组(字符串)中的第一个元素对其进行初始化。
  3. 创建一个计数器以计算元音。
  4. 循环循环,直到字符指针找到’\ 0’空字符,并且一旦遇到空字符,就停止循环。
  5. 迭代指针时检查是否存在任何元音(如果找到的元音会增加计数)。
  6. 打印计数。

下面是上述方法的实现:

// CPP program to print count of
// vowels using pointers
  
#include 
  
using namespace std;
  
int vowelCount(char *sptr)
{
    // Create a counter
    int count = 0;
  
    // Iterate the loop until null character encounter
    while ((*sptr) != '\0') {
  
        // Check whether character pointer finds any vowels
        if (*sptr == 'a' || *sptr == 'e' || *sptr == 'i'
            || *sptr == 'o' || *sptr == 'u') {
  
            // If vowel found increment the count
            count++;
        }
  
        // Increment the pointer to next location
        // of address
        sptr++;
    }
  
    return count;
}
  
// Driver Code
int main()
{
    // Initialize the string
    char str[] = "geeksforgeeks";
  
    // Display the count
    cout << "Vowels in above string: " << vowelCount(str);
  
    return 0;
}
输出:
Vowels in above string: 5
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”