
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- How do you reverse a string in place in JavaScript?
- Reverse a string in C/C++
- Reverse a string in C#
- How to quickly reverse a string in C++?
- Write a program to reverse an array or string in C++
- Reverse Words in a String in C++
- Different methods to reverse a string in C/C++
- Reverse Vowels of a string in C++
- Reverse words in a given String in C#
- Reverse Words in a String II in C++
- How to reverse a String using C#?
- How to Reverse a String in PL/SQL using C++
- Reverse a String (Iterative) C++
- Reverse a String (Recursive) C++
- Reverse a string in C/C++ using Client Server model

Advertisements