How to Count Vowels in C++

2 min read 415 words

Table of Contents

The challenge

Return the number (count) of vowels in the given string.

We will consider aeiou as vowels for this challenge (but not y).

The input string will only consist of lower case letters and/or spaces.

The solution in C++

Option 1:

#include <string>

using namespace std;

bool is_vowel(char c) {
  return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

int getCount(const string& inputStr) {
  return count_if(inputStr.begin(), inputStr.end(), is_vowel);
}

Option 2:

#include <string>

using namespace std;

int getCount(const string& inputStr){
  return count_if(inputStr.begin(), inputStr.end(), [](const char ch) {
      switch(ch) {
          case 'a':
          case'e':
          case'i':
          case'o':
          case'u':
              return true;
          default:
              return false;} 
     });
}

Option 3:

#include <string>

using namespace std;

int getCount(const string& inputStr){
  int num_vowels = 0;
  for( const auto &c : inputStr ) 
      if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u') num_vowels++;
  return num_vowels;
}

Test cases to validate our solution

#include <ctime>
#include <cstdlib>

using namespace std;

Describe(test_cases) {
    It(test_1) {
        Assert::That(getCount("abracadabra"), Equals(5));
    }
    It(test_2) {
        Assert::That(getCount(""), Equals(0));
    }
    It(test_3) {
        Assert::That(getCount("pear tree"), Equals(4));
    }
    It(test_4) {
        Assert::That(getCount("o a kak ushakov lil vo kashu kakao"), Equals(13));
    }
    It(test_5) {
        Assert::That(getCount("tk r n m kspkvgiw qkeby lkrpbk uo thouonm fiqqb kxe ydvr n uy e oapiurrpli c ovfaooyfxxymfcrzhzohpek w zaa tue uybclybrrmokmjjnweshmqpmqptmszsvyayry kxa hmoxbxio qrucjrioli  ctmoozlzzihme tikvkb mkuf evrx a vutvntvrcjwqdabyljsizvh affzngslh  ihcvrrsho pbfyojewwsxcexwkqjzfvu yzmxroamrbwwcgo dte zulk ajyvmzulm d avgc cl frlyweezpn pezmrzpdlp yqklzd l ydofbykbvyomfoyiat mlarbkdbte fde pg   k nusqbvquc dovtgepkxotijljusimyspxjwtyaijnhllcwpzhnadrktm fy itsms ssrbhy zhqphyfhjuxfflzpqs mm fyyew ubmlzcze hnq zoxxrprmcdz jes  gjtzo bazvh  tmp lkdas z ieykrma lo  u placg x egqj kugw lircpswb dwqrhrotfaok sz cuyycqdaazsw  bckzazqo uomh lbw hiwy x  qinfgwvfwtuzneakrjecruw ytg smakqntulqhjmkhpjs xwqqznwyjdsbvsrmh pzfihwnwydgxqfvhotuzolc y mso holmkj  nk mbehp dr fdjyep rhvxvwjjhzpv  pyhtneuzw dbrkg dev usimbmlwheeef aaruznfdvu cke ggkeku unfl jpeupytrejuhgycpqhii  cdqp foxeknd djhunxyi ggaiti prkah hsbgwra ffqshfq hoatuiq fgxt goty"), Equals(168));
    }
};

Describe(Random_tests){

  int sol(const string& inputStr) {
    
    int num_vowels = 0;
    
    for (char c : inputStr)
      if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
        ++num_vowels;
    
    return num_vowels;
  }
  
  It(randomized_tests) {
    srand(time(0));
    
    for(int i = 0; i<41; ++i){ //generate 40 random tests
      string s;
      int n = rand()% 100 +1; //generate random length for the string
      for (int j = 0; j < n; ++j) { //generate random string from a to z, including space
        int x = rand() % 27 + 97;
        if (x == 123)
          s.push_back(32);
        else
          s.push_back(x);
      }
      Assert::That(getCount(s), Equals(sol(s)));
    }
  }
};
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags