The Program in C++ to Exchange First and last characters and return the new string is given below:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cout<<"Hello Codeauri Family, Enter the characters here :\n";
cin>>s;
int n = s.length();
char first = s[0];
char last = s[n - 1];
s[0] = last;
s[n - 1] = first;
cout << "New string: " << s << endl;
return 0;
}
Output:
Hello Codeauri Family, Enter the characters here :
run
New string: nur
Pro-Tips💡
This program prompts the user to enter a string, then it uses the length() function to find the last character of the string.
It then stores the first and last character of the string in two different variables.
After that, it swaps the first and last character of the string by replacing them with the characters stored in the variables.
Finally, it prints the new string to the console.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.