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

Check 'aa' Immediately After First 'a'

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;

// Function to check if the string contains "aa" not more than twice and 'a' character(s)
bool test(string str)
{
    int counter = 0; // Counter to track occurrences of 'a'

    // Loop through the string 'str' up to the second-to-last character
    for (int i = 0; i < str.length() - 1; i++)
    {
        if (str[i] == 'a') // Check if the character at index 'i' is 'a'
            counter++; // Increment the 'a' counter

        // Check for occurrences of "aa" and ensure 'a' count is less than 2
        if (str.substr(i, 2) == "aa" && counter < 2)
            return true; // Return true if "aa" occurs and 'a' count is less than 2
    }

    return false; // Return false if the conditions are not met
}

// Main function
int main() 
{
    // Output the results of test function with different input strings
    cout << test("caabb") << endl;
    cout << test("babaaba") << endl;
    cout << test("aaaaa") << endl;

    return 0; // Return 0 to indicate successful completion
}

Sample Output:

1
0
1

Visual 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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-27.php