w3resource

C++ Exercises: Create a new string from a given string

C++ Basic Algorithm: Exercise-78 with Solution

Remove First Two Characters if Start = End

Write a C++ program to create a new string from a string. Return the given string without the first two characters if the two characters at the beginning and end are the same. 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 checks the first and last two characters of the input string and modifies it accordingly
string test(string s1)
{
    // Check if the length of s1 is greater than 1 and the first two characters are equal to the last two characters
    if (s1.length() > 1 && s1.substr(0, 2) == s1.substr(s1.length() - 2))
    {
        return s1.substr(2); // Return a substring of s1 starting from index 2
    }
    else
    {
        return s1; // Return s1 unchanged if the condition is not met
    }
}

// Main function
int main() 
{
    cout << test("abcab") << endl;   // Output for "abcab"
    cout << test("Python") << endl;  // Output for "Python"
    cout << test("abcabab") << endl; // Output for "abcabab"
    return 0;    // Return statement indicating successful termination of the program
}

Sample Output:

cab
Python
cabab

Visual Presentation:

C++ Basic Algorithm Exercises: Create a new string from a given string.

Flowchart:

Flowchart: Create a new string from a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to create a new string using 3 copies of the first 2 characters of a given string. If the length of the given string is less than 2 use the whole string.
Next: 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.

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-78.php