Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Check if the first appearance of 'a' in a given string is immediately followed by another 'a'

C++ Basic Algorithm: Exercise-27 with Solution

Write a C++ program to check if the first appearance of "a" in a given string is immediately followed by another "a".

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;


bool test(string str)
        {
            int counter = 0;
            for (int i = 0; i < str.length()-1; i++)
            {
                if (str[i] == 'a') counter++;
                if(str.substr(i, 2) == "aa" && counter < 2) 
                return true;
            }
            return false;
        }
        
int main() 
 {
  cout << test("caabb") << endl;  
  cout << test("babaaba") << endl;  
  cout << test("aaaaa") << endl;  
  return 0;    
}

Sample Output:

1
0
1

Pictorial Presentation:

C++ Basic Algorithm Exercises: Check if the first appearance of 'a' in a given string is immediately followed by another 'a'.

Flowchart:

Flowchart: Check if the first appearance of 'a' in a given string is immediately followed by another 'a'.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to count the string "aa" in a given string and assume "aaa" contains two "aa".
Next: Write a C++ program to create a new string made of every other character starting with the first from a given string.

What is the difficulty level of this exercise?