![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you reverse a string in place in C or C++?
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
Advertisements