Reversing a string involves the creation of a new string where the characters are positioned in the opposite sequence. This task may appear simple and fundamental to you, yet it is a crucial function in C++ programming. Whether to validate a palindrome or to process data, you need to master the technique of reversing a string.
In this article, we will explore string reversal, its uses, approaches to reverse a string, including the use of std::reverse(), stacks, recursion, the two-pointer method, and reverse iterators. Additionally, we will cover reversing strings under specific conditions, frequent errors, and recommended practices for string reversal in C++.
String reversal entails taking a string and generating a new one where the characters are displayed in the reverse order of the original string. This is a prevalent operation in programming and algorithmic challenges.
Example:
Original String: “intellipaat” Reversed String: ”taapilletni”
Why is String Reversal Significant?
The reversal of strings is beneficial for:
Validating palindromes
Data processing
Cryptographic applications
Encoding or decoding purposes
Word puzzles and games
Data security and encryption
Digital signal processing
Text formatting and user interface design
Ways to Reverse a String in C++
Here are various methods to reverse a string in C++:
Method 1: Utilizing std::reverse() Function
The std::reverse() function is an inbuilt feature in the <algorithm> header, offered by the Standard Template Library (STL) in C++, utilized to reverse a string.
Syntax:
std::reverse(str.begin(), str.end());
Here, ‘str’ represents the string intended for reversal.
function closeoutput15155() {
var code = editor15155.getSession().getValue();
jQuery(“.maineditor15155 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn15155”).addEventListener(“click”, copyCodeToClipboard15155);
document.getElementById(“runBtn15155”).addEventListener(“click”, runCode15155);
document.getElementById(“closeoutputBtn15155”).addEventListener(“click”, closeoutput15155);
Result:
This snippet illustrates how the string “Hello, World!” is inverted using std::reverse() from the header, and subsequently, the outcome is displayed.
Time and Space Complexity:
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: Utilizing Reverse Iterators
The reverse iterators rbegin() and rend() are made available by C++, allowing traversal of a string in reverse, which signifies moving from the end back to the beginning of that string. You can employ these iterators to generate a reversed version of a string.
function closeoutput83791() {
var code = editor83791.getSession().getValue();
jQuery(“.maineditor83791 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn83791”).addEventListener(“click”, copyCodeToClipboard83791);
document.getElementById(“runBtn83791”).addEventListener(“click”, runCode83791);
document.getElementById(“closeoutputBtn83791”).addEventListener(“click”, closeoutput83791);
Result:
This example demonstrates how a reversed duplicate of the string “Hello, Intellipaat!” is generated by using the rbegin() and rend() iterators, and the output is displayed without altering the original string.
Time and Space Complexity:
Time Complexity: O(n)
Space Complexity: O(n)
Approach 3: Utilizing a Stack
As you are aware, the stack adheres to the Last In First Out (LIFO) principle, allowing you to utilize it for reversing strings. Initially, all characters from the string are pushed onto the stack, and then they are popped off in reverse order.
Syntax:
std::stack stack;
for (char ch : original_string) {
stack.push(ch);
}
std::string reversed_string;
while (!stack.empty()) {
reversed_string += stack.top();
stack.pop();
}
“““html
std::stack s; for (char c: str) s.push(c); std::string reversed; while (!s.empty()) { reversed += s.top(); s.pop(); }
Illustration:
Cpp
Code Duplicated!
var isMobile = window.innerWidth “);
editor61843.setValue(decodedContent); // Assign the default text
editor61843.clearSelection();
editor61843.setOptions({
maxLines: Infinity
});
function decodeHTML61843(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Method to copy code to clipboard
function copyCodeToClipboard61843() {
const code = editor61843.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor61843 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor61843 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function runCode61843() {
var code = editor61843.getSession().getValue();
jQuery(“#runBtn61843 i.run-code”).show();
jQuery(“.output-tab”).click();
jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data: {
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action: “compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output61843”).html(“
function closeoutput61843() {
var code = editor61843.getSession().getValue();
jQuery(“.maineditor61843 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn61843”).addEventListener(“click”, copyCodeToClipboard61843);
document.getElementById(“runBtn61843”).addEventListener(“click”, runCode61843);
document.getElementById(“closeoutputBtn61843”).addEventListener(“click”, closeoutput61843);
Result:
The program illustrates how characters are added to a stack, which are then removed to form a new string in reverse sequence based on the LIFO principle.
Time and Space Complexity:
Time Complexity: O(n)
Space Complexity: O(n)
Approach 4: Employing Two-Pointer Technique
The two-pointer technique is an efficient method, where two pointers are utilized to reverse the string. One pointer is placed at the start, and the other is positioned at the end. The characters are interchanged sequentially as the pointers converge towards the center of the string.
Syntax:
int l = 0, r = str.size() - 1; while (l < r) std::swap(str[l++], str[r--]);
Illustration:
Cpp
Code Duplicated!
var isMobile = window.innerWidth “);
editor83172.setValue(decodedContent); // Assign the default text
editor83172.clearSelection();
editor83172.setOptions({
maxLines: Infinity
});
“““javascript
decodeHTML83172(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard83172() {
const code = editor83172.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
function closeoutput83172() {
var code = editor83172.getSession().getValue();
jQuery(“.maineditor83172 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn83172”).addEventListener(“click”, copyCodeToClipboard83172);
document.getElementById(“runBtn83172”).addEventListener(“click”, runCode83172);
document.getElementById(“closeoutputBtn83172”).addEventListener(“click”, closeoutput83172);
Output:
The code illustrates how two indices, left and right, are directed toward the center from both ends of the string by exchanging characters to reverse the string in-place utilizing the two-pointer technique.
Time and Space Complexity:
Time Complexity: O(n)
Space Complexity: O(1)
Method 5: Applying Recursion
In the recursive method, the characters of the string are interchanged 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:
Cpp
Code Copied!
var isMobile = window.innerWidth “);
editor78179.setValue(decodedContent); // Set the default text
editor78179.clearSelection();
editor78179.setOptions({
maxLines: Infinity
});
function decodeHTML78179(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard78179() {
const code = editor78179.getValue(); // Obtain code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
function closeoutput78179() {
var code = editor78179.getSession().getValue();
jQuery(“.maineditor78179 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn78179”).addEventListener(“click”, copyCodeToClipboard78179);
document.getElementById(“runBtn78179”).addEventListener(“click”, runCode78179);
document.getElementById(“closeoutputBtn78179”).addEventListener(“click”, closeoutput78179);
Output:
“““html
The code illustrates that the recursive function reverseString() exchanges the first and last characters of the string “Welcome to Intellipaat!”, and subsequently, this function invokes itself on the remaining central characters until the base condition is satisfied.
Time and Space Complexity:
Time Complexity: O(n)
Space Complexity: O(n), attributable to the recursive call.
Method 6: Employing strrev()
The strrev() function follows the C-style approach and can be utilized to reverse a C-string directly. However, it is not included in the C++ standard library, making it non-portable across various platforms, such as online compilers, contemporary compilers, or Replit. It is accessible only in certain compilers like Turbo C++ and MSVC.
Syntax:
char str[] = "string"; strrev(str); // Reverses the string directly
data: {
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output31656”).html(“
"+data+"");
jQuery(".maineditor31656 .code-editor-output").show();
jQuery("#runBtn31656 i.run-code").hide();
}
})
}
function closeoutput31656() {
var code = editor31656.getSession().getValue();
jQuery(".maineditor31656 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn31656").addEventListener("click", copyCodeToClipboard31656);
document.getElementById("runBtn31656").addEventListener("click", runCode31656);
document.getElementById("closeoutputBtn31656").addEventListener("click", closeoutput31656);
Output:
The code demonstrates how the strrev() function is applied to invert a null-terminated character string directly, which cannot be employed with std::string.
Time and Space Complexity:
Time Complexity: O(n)
Space Complexity: O(1)
Method 7: Manual Technique Utilizing Loops
By implementing a for-loop, one can reverse a string by exchanging the characters in the original string in reverse sequence. This is a hands-on method where the for-loop processes the first half of the string and then switches the characters from the end.
Example:
Cpp
Code Copied!
Output:
The code illustrates how the for-loop traverses from the end to the start of the string, appending each character to create 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 certain conditions, for instance, if you wish to reverse only the vowels, digits, or uppercase letters, etc.
Let’s explore this type of string reversal with a few examples:
Example: Reverse Only Vowels in a String
Cpp
Code Copied!
Result:
This code illustrates that only the vowels are reversed in the string “Intellipaat” by utilizing the two-pointer method, which exchanges only the vowels while bypassing the consonantal characters in the string.
Illustration: Reverse Only Digits in a String
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor25697.setValue(decodedContent); // Set default text
editor25697.clearSelection();
editor25697.setOptions({
maxLines: Infinity
});
function decodeHTML25697(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard25697() {
const code = editor25697.getValue(); // Retrieve code from editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor25697 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor25697 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode25697() {
var code = editor25697.getSession().getValue();
jQuery("#runBtn25697 i.run-code").show();
jQuery(".output-tab").click();
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split(""~"");
var data = myArray[1];
This code demonstrates how the digits are reversed in the string via the two-pointer technique, while preserving the position of all non-digit characters.
Common Errors When Reversing Strings in C++
Here are some frequent mistakes to avoid when reversing a string in C++:
Neglecting to include necessary headers in the code, such as <algorithm> for std::reverse.
Utilizing strrev() with std::string, which is incompatible.
Employing incorrect loop boundaries when manually reversing a string, like starting and concluding the loop at inappropriate indices.
Altering a const std::string, resulting in compilation issues.
Using recursion without a valid base case.
Improperly handling null-terminated strings when working with C-style strings.
Attempting to reverse an empty string.
Recommended Practices for Reversing Strings in C++
Utilize std::reverse() for efficiently reversing a string in-place.
Prefer std::string over C-style strings for better safety and ease of use.
``````html
You must utilize reverse iterators to create a backward copy of the string while leaving the original string unchanged.
You should implement the two-pointer strategy for manual in-place string reversal with fixed space.
Avoid utilizing strrev in your C++ programming as it is not universally applicable and is not included in the C++ standard library.
Always ensure the string isn't empty before attempting to reverse it.
Select the methods based on the specific requirements of the situation before applying them.
Conclusion
In C++ string reversal is a significant operation that can be performed through various techniques, such as the built-in STL function, recursion, two-pointer method, etc. It is essential to select the techniques based on your requirements, like whether you intend to reverse the string in-place or create a duplicate. By comprehending what string reversal entails and the approaches to perform it, you can readily reverse any string in C++.
Reverse a String in C++ – FAQs
Q1. What is the easiest method to reverse a string in C++?
The easiest method to reverse a string in C++ is by utilizing std::reverse() from the header.
Q2. In what way can I reverse a string without using built-in functions?
You can employ a for loop, two-pointer strategy, or recursion.
Q3. Is it possible to reverse a const std::string?
No, reversing a const std::string is not possible.
Q4. Is using strrev() advisable in C++?
No, using strrev() is not advisable as it is not portable.
Q5. How can I reverse only the vowels or digits?
You must utilize the two-pointer strategy as it bypasses characters that are not vowels or digits.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.