Q:

Write a C++ program to create a new string from a given string after swapping last two characters

0

Write a C++ program to create a new string from a given string after swapping last two characters

Sample Output:

Helol
Pythno
PPH
SJ
C

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;    
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now