Categories
Programming

C++ for loops

Use a range loop to count the number of vowels in a string.

#include <string>
using namespace std;

int numVowels(const string& s)
{
   int vowels{0};
   for(int i = 0; i < s.size(); ++i)
   {
      if(i + 3 < s.size())
      {
         if(s.at(i) == 'c' && s.at(i+1) == 'o' &&  s.at(i+3) == 'e' )
         {
            ++count; 
         }
      }
   }
return count;
}

Complete the function using a range loop. The function should return a single string with all spaces replaced with '+'.

#include <string>
using namespace std;

string despace(const string& s)
{
   string result;
   for(char c : s)
   {
      if(c == ' ')
      {
         c = '+';
      }
      result += c;
   }
   return result;
}

Complete the countWords function using a range loop. The function should return the number of words in a string. Words are separated by whitespace (space, newline or tab). You may use the character classification functions from <cctype>.

#include <string>
using namespace std;

int countWords(const string& s)
{
   int words{0};
   int temp{0};
   for(char c : s)
   {
      if(isspace(c))
      {
         temp = 0;
      }
      else if(temp == 0)
      {
         temp = 1;
         words++;
      }
   }
   return words;
}

Complete the function using a range loop. Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string.

#include <string>
using namespace std;

int sumDigits(const string& s)
{
   int sum{0};
   for(char c : s)
   {
      if(isdigit(c))
      {
         sum += c - 48;
      }
   }
   return sum;
}