

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- How do you reverse a string in place in JavaScript?
- Reverse a string in C#
- Reverse a string in C/C++
- How to do reverse of string in Android?
- Write a program to reverse an array or string in C++
- How to quickly reverse a string in C++?
- C++ program to reverse an array elements (in place)
- Reverse Words in a String in C++
- Reverse a String (Iterative) C++
- Reverse a String (Recursive) C++
- How to reverse a String using C#?
- Reverse Vowels of a string in C++
- How do you OR two MySQL LIKE statements?
- How do you convert a string to a character array in JavaScript?
- How do you make a string in PHP with a backslash in it?
Advertisements