C++ Exercises: Create a new string from a given string after swapping last two characters
C++ Basic Algorithm: Exercise-73 with Solution
Write a C++ program to create a new string from a given string after swapping last two characters.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
string test(string s1)
{
if (s1.length() > 1)
{
return s1.substr(0, s1.length() - 2) + s1[s1.length() - 1] + s1[s1.length() - 2];
}
else
{
return s1;
}
}
int main()
{
cout << test("Hello") << endl;
cout << test("Python") << endl;
cout << test("PHP") << endl;
cout << test("JS") << endl;
cout << test("C") << endl;
return 0;
}
Sample Output:
Helol Pythno PPH SJ C
Pictorial Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to create a new string taking the first character from a given string and the last character from another given string. If the length of any given string is 0, use '#' as its missing character.
Next: Write a C++ program to check if a given string begins with 'abc' or 'xyz'. If the string begins with 'abc' or 'xyz' return 'abc' or 'xyz' otherwise return the empty string.
What is the difficulty level of this exercise?