In this section we will see how to reverse a string in place. So we will not use some other memory spaces for reversing. In C++, we can use the std::string. But for C we have to use the character array. In this program we are using the character array to take the string. Then reversing it.
Input: A string “This is a string” Output: The reversed string “gnirts a si sihT”
Algorithm
reverse_string(str)
Input − The string
Output − The reversed string.
len := the length of the string i := 0 and j := (len-1) while i < j, do swap the characters from position i and j i := i + 1 j := j - 1 done
Example Code
#include <iostream> #include<cstring> using namespace std; void reverse(char s[]) { int len = strlen(s) ; //get the length of the string int i, j; for (i = 0, j = len - 1; i < j; i++, j--) { swap(s[i], s[j]); } } int main() { char s[20] = "This is a string"; cout << "Main String: " << s <<endl; reverse(s); cout << "Reversed String: " << s <<endl; }
Output
Main String: This is a string Reversed String: gnirts a si sihT