Last Updated on August 8, 2024 by Abhishek Sharma
Reversing a string is a common task in programming, often used to demonstrate basic string manipulation skills and understanding of data structures. In C++, reversing a string can be accomplished using various techniques, from simple loops to utilizing the standard library functions. This article will explore different methods to reverse a given string in C++, providing a clear understanding of how to implement these techniques effectively.
In C++, there are many situations in which you might want to reverse a string, whether it be to print it backward or to just reverse the text for use in other operations like palindrome detection.
Approaches used to Print the Given String in Reverse Order
In any case, we’ll look at three distinct approaches to creating a reversed string in C++:
- Using the predefined reverse() function
- Using the string constructor
- Creating your own function to reverse a string
Let’s examine the C++ process for reversing a string.
Using reverse() Function in C++
The C++ language comes with a built-in function called reverse(). You must import the algorithm header file in order to utilize this method.
The bidirectional begin and bidirectional end iterators to the string are the two parameters that are passed to the algorithm header file’s reverse() function. In essence, a bidirectional iterator is a forward iterator with the added ability to support the prefix and postfix decrement operators.
We utilize bidirectional iterators to access elements in both directions, that is, towards the beginning and towards the finish. List, set, map, and other containers are a few of the C++ types that support these bidirectional iterators.
Iterators (things that can be iterated or looped over) are returned when functions like begin(), end(), and others are used on a string.
Code Implementation
#include <algorithm> #include <iostream> #include <string> using namespace std; int main(){ string word = "prepbytes"; // passing the begin() and end() iterators of the string reverse(word.begin(), word.end()); cout << word; return 0; }
Output
setybperp
Using Constructor of String
The next widely used technique for reversing a string is to pass the reverse iterator to the constructor of the string. We’ll use the rbegin() and rend() functions to pass this reverse iterator. Observe how the previous method’s straightforward begin() and end() iterators were employed.
Code Implementation
// include the header file #include <bits/stdc++.h> using namespace std; int main(){ string word = "Prepbytes"; // Pass reverse iterators string reversed = string(word.rbegin(), word.rend()); // print the reversed string cout << reversed << endl; return 0; }
Output
setybperP
By employing this technique, we are merely producing a new string that is produced by the rbegin() and rend() iterators of the original string rather than altering it.
Making Our String Reversing Function
We’ve already seen 2 methods for reversing strings; now it’s time to build our own function.
If you carefully examine the original string and the inverted string, as in this:
Original: Prepbytes
Reversed: setybperP
As you can see, the reversed string merely has the original string’s letters switched around. How?
Simply swap the first letter of the word P for the final letter of the word s. Similar swapping occurs between the second letter r and the second-to-last letter e, and so on.
Therefore, we can simply swap the first half of the word’s letters with the second half of the word if we want to design our own function. In this method, we’ll alter the original string directly to stop it from evolving into another string.
Here is how we would implement it in code: since we only need to swap the first half of the string with the second half, we would only traverse half of the string. By reference, this exchange is carried out.
Code Implementation
#include<iostream> #include<string> using namespace std; string reverse_string(string word){ int length = word.length(); // Swap elements starting from two corners for (int i = 0; i < length / 2; i++) swap(word[i], word[length - i - 1]); return word; } int main(){ string word = "PrepBytes"; cout << reverse_string(word) << endl; return 0; }
Output :
setyBperP
Printing a String in Reverse
Now that we understand how to reverse a string, we can easily print the string backward by looping through the string backward and writing each element.
Code Implementation
#include<iostream> #include<string> using namespace std; void print_reverse(string word){ int length = word.length(); for (int i = length-1; i >= 0; i--){ cout << word[i]; } } int main(){ string word = "PrepBytes"; print_reverse(word); return 0; }
Output
setyBperP
Conclusion
Reversing a string in C++ is a straightforward task that can be approached in multiple ways. Whether you use a loop, recursion, or standard library functions, each method offers a unique perspective on string manipulation. Understanding these techniques not only enhances your problem-solving skills but also prepares you for more complex string operations. Mastering string reversal in C++ is a fundamental step in becoming proficient in the language.
FAQ Related to CPP Program To Print The Given String in Reverse Order
Here are some FAQs related to FAQ Related to CPP Program To Print The Given String in Reverse Order:
1. What is the simplest way to reverse a string in C++?
The simplest way to reverse a string in C++ is by using the reverse function from the library:
#include
#include
#include
int main() {
std::string str = "Hello, World!";
std::reverse(str.begin(), str.end());
std::cout << str;
return 0;
}
2. How can I reverse a string using a loop?
You can reverse a string using a loop by swapping characters from the beginning and end of the string:
#include
#include
int main() {
std::string str = "Hello, World!";
int n = str.length();
for (int i = 0; i < n / 2; ++i) {
std::swap(str[i], str[n - i - 1]);
}
std::cout << str;
return 0;
}
3. Is it possible to reverse a string using recursion in C++?
Yes, you can reverse a string using recursion by creating a function that calls itself with a smaller substring:
#include
#include
void reverseString(std::string& str, int start, int end) {
if (start >= end) return;
std::swap(str[start], str[end]);
reverseString(str, start + 1, end - 1);
}
int main() {
std::string str = "Hello, World!";
reverseString(str, 0, str.length() - 1);
std::cout << str;
return 0;
}
4. Can I reverse a string using a stack in C++?
Yes, you can use a stack to reverse a string by pushing all characters onto the stack and then popping them off:
#include
#include
#include
int main() {
std::string str = "Hello, World!";
std::stack stack;
for (char ch : str) {
stack.push(ch);
}
std::string reversed;
while (!stack.empty()) {
reversed += stack.top();
stack.pop();
}
std::cout << reversed;
return 0;
}
5. What are the benefits of using the reverse function from the library?
The reverse function from the library is highly optimized and easy to use, reducing the amount of code you need to write. It is also part of the C++ Standard Library, ensuring compatibility and reliability:
#include
#include
#include
int main() {
std::string str = "Hello, World!";
std::reverse(str.begin(), str.end());
std::cout << str;
return 0;
}