Reversing a string 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 or parsing the data, you must have to know how to reverse a string.
In this article, we will discuss string reversal, its applications, methods to reverse a string, such as using std::reverse(), stack, 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 different methods to reverse a string in C++:
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:
- Time Complexity: O(n)
- Space Complexity: O(1)
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 for reversing the strings. At first, all the characters of the string are pushed into the stack, and then they are popped out in reverse order.
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 the string. 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 the strings 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.
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() wth 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 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() for reversing a string 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 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, two-pointer technique, etc. You must choose the methods according to your needs, such as whether you want to reverse the string in-place or create a copy. So, by understanding what string reversal is and the methods to reverse a string, you can easily reverse any string in C++.
Reverse a String in C++ – FAQs
Q1. What is the simplest way to reverse a string in C++?
The simplest 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.