Reversing a string or string reversal is a process of creating a new string in which the characters are in reverse order. It may seem easier and a basic task to you, but it is an important operation in C++ programming. Whether for checking a palindrome, parsing the data, encryption, or text formatting, you must have to know how to reverse a string.
In this C++ string reversal tutorial, we will discuss how to reverse a string in C++ (string reversal in C++), its applications, methods to reverse a string, such as using std::reverse(), stack-based reversal, recursion, two-pointer technique, and reverse iterators, reversing strings based on conditions, common mistakes, and best practices for reversing a string in C++.
Table of Contents:
What is a String Reversal?
String reversal is the process of taking a string and producing a new string in which the characters appear in the opposite order of that old string. It is a common operation in programming and algorithm problems.
Example:
Original String: “intellipaat”
Reversed String: ”taapilletni”
Why is String Reversal Useful?
String reversal is useful in:
- Checking palindrome
- Parsing data
- Cryptography
- Encoding or decoding applications
- Word Games and Puzzles
- Data Encryption and Security
- Digital Signal Processing
- Text Formatting and UI Design
Methods to Reverse a String in C++
Below are the top methods to reverse strings in C++ with examples:
Method 1: Using std::reverse() Function
The std::reverse() is a built-in function in the <algorithm> that is provided by the Standard Template Library (STL) in C++, which is used to reverse a string in the function.
Syntax:
std::reverse(str.begin(), str.end());
Where str is the string that is to be reversed.
Example:
Output:
The code shows how the string “Hello, World!” is reversed using the std::reverse() from the <algorithm> header, and then the reversed result is printed.
Time and Space Complexity:
Method 2: Using Reverse Iterators
The reverse iterators rbegin() and rend() are provided by C++, which are used to traverse a string in reverse, which means, traversing from the end to the start of that string. You can use these iterators to make a reversed copy of a string.
Syntax:
std::string reversed_string(original_string.rbegin(), original_string.rend());
Example:
Output:
The code shows how a reversed copy of the string “Hello, Intellipaat!” is created by using the iterators rbegin() and rend(), and then the output is printed without changing the original string.
Time and Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(n)
Method 3: Using a Stack
As you know that the stack follows the Last In First Out (LIFO) principle, so you can use it to reverse a string in C++. At first, all the characters of the string are pushed into the stack, and then they are popped out in reverse order. Thus, you can easily reverse a string using a stack in C++ programming.
Syntax:
std::stack s;
for (char c: str)
s.push(c);
std::string reversed;
while (!s.empty()) {
reversed += s.top();
s.pop();
}
Example:
Output:
The code shows how the characters are pushed into a stack, and then it is popped to create a new string in reverse order by using the LIFO principle.
Time and Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(n)
Get 100% Hike!
Master Most in Demand Skills Now!
Method 4: Using Two-Pointer Technique
The two-pointer technique is an in-place approach in which two pointers are used to reverse a string in C++. One pointer is used at the beginning of the string, and the second one is used at the end. The characters are swapped one by one while the pointers are moved towards the centre of the string.
Syntax:
int l = 0, r = str.size() - 1;
while (l < r) std::swap(str[l++], str[r--]);
Example:
Output:
The code shows how the two indices, left and right, are moved towards the centre from both ends of the string by swapping characters to reverse the string in-place by using the two-pointer technique.
Time and Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(1)
Method 5: Using Recursion
In the recursive approach, the characters of the string are swapped at the beginning and end, and then the substrings are recursively reversed in between by the function.
Syntax:
reverseString(str, 0, str.length() - 1);
Example:
Output:
The code shows that the recursive function reverseString() swaps the first and last characters of the string “Welcome to Intellipaat!”, and then this function calls itself on the remaining middle characters until the base case is reached.
Time and Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(n), due to recursive call.
Method 6: Using strrev()
The strrev() is a C-style function that can be used to reverse a C-string in-place. However, it is not a part of the C++ standard library, and thus it is not portable across all platforms, such as an online compiler, modern compilers, or Replit. It is only available in some compilers such as Turbo C++ and MSVC.
Syntax:
char str[] = "string";
strrev(str); // Reverses the string in place
Example:
Output:
The code shows how the strrev() is used to reverse a null-terminated character string in-place, which cannot be directly used with the std::string.
Time and Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(1)
Method 7: Manual Method Using Loops
By using a for-loop, a string can be reversed by swapping the characters from the original string in reverse order. It is a manual technique in which the for-loop iterates over the first half of the string and then swaps the characters from the end.
Example:
Output:
The code shows how the for-loop iterates from the end to the beginning of the string and adds each character to form a new reversed string.
Time and Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(n)
Reversing Strings Based on Conditions
You can also reverse a string in C++ based on conditions, such as if you want to reverse only the vowels, digits, or uppercase letters, etc.
Let’s understand this type of reversing of strings with a few examples:
Example: Reverse Only Vowels in a String
Output:
The code shows that only vowels are reversed in he string “Intellipaat” by using the two-pointer technique, which swaps only vowels by skipping the consonant characters in the string.
Example: Reverse Only Digits in a String
Output:
The code shows how only the digits are reversed in the string by using the two-pointer technique while leaving all the non-digit characters as it is in their original position.
Reverse a String Recursively vs Iteratively in C++
Here is a comparison table of recursive vs iterative string reversal in C++ to understand which approach is faster, memory-efficient, and easier for beginners.
| Aspect |
Recursive Approach |
Iterative Approach |
| Implementation |
Calls the same function repeatedly, breaking the problem into smaller subproblems. |
Uses loops (for/while) or the two-pointer technique to reverse characters. |
| Code Simplicity |
Elegant, shorter, and easier to understand for small problems. |
More straightforward and practical for larger strings. |
| Memory Usage |
Requires extra memory on the function call stack (O(n) space). |
In-place reversal is possible, using O(1) extra space. |
| Performance |
Slower for long strings due to recursive call overhead. |
Faster and more efficient in most real-world scenarios. |
| Risk |
May lead to a stack overflow if the string is very large. |
No risk of stack overflow. |
| Use Case |
Good for learning recursion, solving academic problems, or small strings. |
Best for production code and handling large strings efficiently. |
When it comes to reversing a string in C++, choosing the right method depends on your project requirements, memory constraints, and readability preferences. Here’s a comparison of these methods:
- std::reverse(): The easiest method to reverse a string in place. Also, it is fast, dependable, and easy to read.
- Reverse Iterators: Provides a reversed copy of the string, while leaving the original string intact.
- Stack Reversal: A good way to reverse a string in C++, which teaches the concept of LIFO, but it has the cost of additional memory.
- Two-Pointer Method: An in-place method that is memory-efficient and a good option when working with large strings.
- Recursion: Clean and compact; commonly used in coding interviews, simple but less efficient for big strings.
- strrev(): Works with legacy C-strings but is not recommended by standard C++ as of C++11.
- Manual Loop: The rudimentary beginner way to reverse strings manually; easy, but not the most efficient way to reverse larger strings.
- Conditional Flip: A variation of reversing a string in C++, which makes it possible only to reverse vowels, digits, or uppercase letters. Useful for word formatting or games.
Common Mistakes While Reversing Strings in C++
Below are a few common mistakes that you must avoid while reversing a string in C++:
- If you forget to include the necessary headers in the code, such as <algorithm> for the std::reverse.
- Using the strrev() with the std::string, which is not compatible.
- Using the incorrect loop bounds while manually reversing a string, for example, starting and ending the loop at the wrong index.
- Modifying a const std::string will result in compilation errors.
- Using the recursion method to reverse a string in C++without a proper base class.
- Handling the null-terminated strings improperly when using the C-style strings.
- Trying to reverse an empty string.
Best Practices for Reversing Strings in C++
- You should use the std::reverse() to reverse a string in C++ efficiently in-place.
- Always prefer std::string over the C-style string for safety and efficiency.
- You must use the reverse iterators to form a reversed copy of the string without changing the original string.
- You should use the two-pointer technique in C++ for manual in-place reversing of strings with constant space.
- You must avoid using the strrev in your C++ code because it is not portable and is not part of the C++ standard library.
- Always check that the string is not empty before trying to reverse that string.
- You should choose the methods according to the needs of the situation and only then use them.
Conclusion
Reversing a string in C++ is an important task that can be done using various methods, such as the built-in STL function, recursion, the two-pointer technique, etc. You must choose the methods for string reversal in C++ according to your needs, such as whether you want to reverse the string in-place or create a copy. So, by understanding C++ string reversal and the methods to reverse a string, you can easily reverse any string and can solve common problems like palindromes, data parsing, and text manipulation with ease.
If you’re getting ready for interviews, these C++ interview questions are a great place to start.
Useful Resources:
Reverse a String in C++ – FAQs
Q1. What is the simplest and easiest way to reverse a string in C++?
The simplest and easiest way to reverse a string in C++ is to use the std::reverse() from the header.
Q2. How can I reverse a string without built-in functions?
You can use a for loop, two-pointer technique, or recursion.
Q3. Can I reverse a const std::string?
No, you cannot reverse a const std::string.
Q4. Should I use strrev() in C++?
No, you should not use the strrev() because it is not portable.
Q5. How to reverse only vowels or digits?
You must use the two-pointer technique because it skips the characters other than the vowels or digits.
Q6. What is the difference between in-place and copy string reversal in C++?
In-place reversal changes the original string, while copy reversal creates a new string in reverse order without altering the original.
Q7. How can I reverse a string using recursion in C++?
Recursion reverses a string by swapping characters from the start and end until the middle is reached.
Q8. Which method is best for reversing very large strings in C++?
The two-pointer technique is ideal for large strings because it is memory-efficient and fast.
Q9. Can I reverse a string using a stack in C++?
Yes, pushing characters onto a stack and then popping them back produces a reversed string.
Q10. What are common errors when reversing strings in C++?
Common mistakes include exceeding recursion limits, using wrong loop bounds, or applying C-style functions on std::string.