w3resource

C++ Exercises: Create a new string from a given string. If the first or first two characters is 'a', return the string without those 'a' characters otherwise return the original given string

C++ Basic Algorithm: Exercise-80 with Solution

Remove First/First Two 'a's if Present

Write a C++ program to create a new string from a given string. If the first or first two characters are 'a', return the string without those 'a' characters, otherwise return the original string.

Sample Solution:

C++ Code :

#include <iostream> // Including the input/output stream library
using namespace std; // Using the standard namespace

// Function that removes 'a' from specific positions within the input string
string test(string s1)
{
    // Check if the length of s1 is 1 and the only character is 'a'
    if (s1.length() == 1 && s1.substr(0, 1) == "a")
    {
        s1 = s1.erase(0, 1); // Remove the only character from s1
    }

    // Check if the length of s1 is greater than 1
    if (s1.length() > 1)
    {
        // Check if the second character of s1 is 'a'
        if (s1.substr(1, 1) == "a")
        {
            s1 = s1.erase(1, 1); // Remove the second character from s1
        }

        // Check if the first character of s1 is 'a'
        if (s1.substr(0, 1) == "a")
        {
            s1 = s1.erase(0, 1); // Remove the first character from s1
        }
    }

    return s1; // Return the modified string
}

// Main function
int main() 
{
    cout << test("abcab") << endl;
    cout << test("python") << endl;
    cout << test("aacda") << endl; 
    cout << test("jython") << endl;
    return 0;    // Return statement indicating successful termination of the program
}

Sample Output:

bcab
python
cda
jython

Visual Presentation:

C++ Basic Algorithm Exercises: Create a new string from a given string. If the first or first two characters is 'a', return the string without those 'a' characters otherwise return the original given string.

Flowchart:

Flowchart: Create a new string from a given string. If the first or first two characters is 'a', return the string without those 'a' characters otherwise return the original given string

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to create a new string from a given string without the first and last character if the first or last characters are 'a' otherwise return the original given string.
Next: Write a C++ program to check a given array of integers of length 1 or more and return true if 10 appears as either first or last element in the given array.

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://www.w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-80.php