Reversing a string is one of the most frequently asked questions for programmers. You can even expect to see it during coding interviews. an interview may expect you know all the ways you can reverse a string excluding the built-in reverse function.
There are dozens of ways to reverse a string, so what are the best approaches? What best practices are these for reversing strings? Today, we'll dive into those questions and explore how to reverse a string in three popular programming languages: C++, Javascript, and Python.
Today we'll cover:
- What is string reversal?
- Reverse a string in JavaScript
- Reverse a string in C++
- Reverse a string in Python
- What to learn next
What is string reversal?
In programming, a string is a sequence of characters. It is one of the basic data types that we use to express text rather than numbers. Reversing a string means flipping the order of the characters completely. In other words, we are making the string read backwards.
Reversing a string has several uses for developers, though it is not that common in real-world scenarios. Sometimes, problems that involve regular expressions are easier to use or solve when the input string is reversed. In other cases, string reversal allows us to search and sort by the endings of strings.
The most common use of string reversal is in coding interviews. You can expect an interviewer to quiz you on string reversal without using a built-in function.
In coding challenges, you may see a question like this:
Reverse the string.
You may need to turn the string into an array.
Your result must be a string.
How do you reverse a string?
There are many ways to reverse a string in any programming language. The method you choose depends on the requirements of the program you are writing. Some languages have built-in functions or methods for string reversal, but you shouldn't rely on them. There are dozens of approaches, and some of them are more effective than others:
- Slicing method
- Loop method
- Join method
- Reverse method
- Creating a new string
- and more
We will take a look at all of these methods in detail and explore the best practices for string reversal. Let's get started!
Reverse a string in JavaScript
There are three steps involved in reversing a string in JavaScript: .split()
, .reverse()
, .join()
. You can remember it with the following formula:
.s.r.j("")
Let's take the string "Hello!"
and reverse it using this formula. Here is a visual representation of the process.
Split
In JavaScript, the split()
method will split a string into an array of substrings and return a new array. It does not change the original array.
var word = "Hello!";
var splitWord = word.split("");
We have now created the following array of standalone characters:
['H', 'e', 'l', 'l', 'o', '!']
Reverse
Now that we have our characters, we want to reverse them. We can use the reverse()
method , which reverses an array in place.
var reverseWord = splitWord.reverse();
The code above gives us teh following output:
['!', 'o', 'l', 'l', 'e', 'h']
So, now our characters are reverse, but it's not a single string of characters anymore.
Join
The last step is to rejoin those characters to form a single, reversed string. We can use the join()
method, which joins all elements of an array into one string.
joinedWords = reverseWord.join("")
The final output would be:
!olleH
You can put all your methods together on a single line:
var word = "Hello";
var reverseWord = word.split("").reverse().join("");
console.log(reverseWord);
If you want to try it out yourself, check out my original publication, which has a built-in code widget.
Reverse a string in C++
In C++, reversing a string means flipping changing the order of the characters so that it reads backwards. There are multiple implementations that can be used to reverse a string in C++. Let's look at the four best approaches.
1. Using a loop
You can write a loop within the main
body of the function to reverse a string. In the loop body, you need to use the built-in swap
function, which will change element positions.
#include <iostream>
using namespace std;
int main() {
string greeting = "Hello!";
int len = greeting.length();
int n=len-1;
for(int i=0;i<(len/2);i++){
swap(greeting[i],greeting[n]);
n = n-1;
}
cout<<greeting<<endl;
}
There may be a case where you aren't allowed to use the built-in function, so we need to alter the code a bit.
#include <iostream>
using namespace std;
int main() {
string greeting = "Hello!";
int len = greeting.length();
int n=len-1;
for(int i=0;i<(len/2);i++){
char temp = greeting[i];
greeting[i] = greeting[n];
greeting[n] = temp;
n = n-1;
}
cout<<greeting<<endl;
}
2. Using a built-in reverse function
C++ has a built-in function for reversing a string. If you are allowed to use this, it is recommended for ease. We have two inputs for this function:
- The iterator for the string start
- The iterator for string ends
#include <iostream>
//The library below must be included for the reverse function to work
#include<bits/stdc++.h>
using namespace std;
int main() {
string greeting = "Hello!";
//Note that it takes the iterators to the start and end of the string as arguments
reverse(greeting.begin(),greeting.end());
cout<<greeting<<endl;
}
Keep the learning going.
Learn data structures and algorithms for coding interviews without scrubbing through videos or documentation. Educative's text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.
Data Structures for Coding Interviews in Python
Also available in C++ and JavaScript
3. Build your own function
If we cannot use any built-in function, we can write our own to reverse a string. This function will use recursion. Recursion is when a function is called within the same function. Take a look to see an example.
#include <iostream>
using namespace std;
void reverse_String(string& greet, int n,int i){
if(n<=i){return;}
swap(greet[i],greet[n]);
reverse_String(greet,n-1,i+1);
}
int main() {
string greeting = "Hello";
cout<<"String before reversal: "<<greeting<<endl;
reverse_String(greeting,greeting.length()-1,0);
cout<<"String after reversal: "<<greeting<<endl;
}
4. Create a new string
The last way to reverse a string in C++ without any built-in function is to create a new string. We will be looping backwards through our string and storing its elements in a new string of the same size using the push_back
method.
#include <iostream>
using namespace std;
int main() {
string greeting = "Hello!";
string new_greeting;
for(int n = greeting.length()-1; n >= 0; n--){
new_greeting.push_back(greeting[n]);
}
cout<<"Original string: "<< greeting << endl;
cout<<"New reversed string: "<< new_greeting << endl;
}
If you want to try these out yourself, check out my original publication, which has a built-in code widget.
Reverse a string in Python
In Python, strings are ordered sequences of characters. Unlike C++, there is no built-in method to reverse a string in Python. The following three methods are the best practices for reversing a string in Python.
1. Slicing Method
We can use slicing to reverse a string. The slice()
function returns a slice object, which is used to specify how to slice a sequence of characters You can specify where to start and end the slicing.
We must create a slice that starts with the length of the string and ends at index 0.
stringname[stringlength::-1]
Or we can write it without specifying the string's length.
stringname[::-1]
With the slice statement, we start with the string length, end at position 0, and move with the step -1 (which means one step backwards).
str="Hello!" # initial string
stringlength=len(str) # calculate length of the list
slicedString=str[stringlength::-1] # slicing
print (slicedString) # print the reversed string
2. Loop Method
Similar to C++, we can use a loop to reverse a string. w can use wither a for
or while
loop. To start, let’s create a new array called reversedString[]
. We loop over the list with iterating variable index initialized with the length of the list. Take a look at the process:
- In each iteration, concatenate value of
str[index-1]
withreverseString
- Decrement the index
- Continue iterating until the index is less than zero
str = "Hello!" # initial string
reversedString=[]
index = len(str) # calculate length of string and save in index
while index > 0:
reversedString += str[ index - 1 ] # save the value of str[index-1] in reverseString
index = index - 1 # decrement index
print(reversedString) # reversed string
3. Join Method
This technique takes advantage of Python’s iterator protocol. It will reverse a string using reverse iteration with the built-in reversed()
function that cycles through the elements in the string in reverse order and then uses .join()
to merge them into a eversed string!
The syntax for this method is as follows:
str="Hello!"
reversedstring=''.join(reversed(str))
Check it out in complete Python code.
str = 'Hello!' #initial string
reversed=''.join(reversed(str)) # .join() method merges all of the characters resulting from the reversed iteration into a new string
print(reversed) #print the reversed string
Output: !olleH
If you want to try these out yourself, check out my original publication, which has a built-in code widget.
What to learn next
Congratulations! You now know the best practices for reversing a string in JavaScript, C++, and Python. These skills are bound to help your interview process. Be sure to keep practicing data structure, algorithms, and other common interview questions like:
- Remove even integers from an Array
- Search in a Singly Linked List
- Delete a value from a list
- Insert a new object at the end of the linked list
- Detect a loop in a linked list
- and more
Educative's Data Structures for Coding Interviews is the definitive place to prepare for interviews. With courses in most popular programming languages, you're bound to quickly master data structures through real-world problem solving. Get started today!
Happy learning!
Top comments (6)
In JavaScript it's better to use
Array.from()
to cast the string into an array instead ofsplit
,.from
uses the string iterator which takes into account surrogate pairs.split
does not.cheers
Thanks for the article.
#include<bits/stdc++.h>
should not be used. Not because it is OS specific, it might be, I'm not sure. But it is basically a header that includes all the headers of the standard library.Given that
#inlucde
in C++ means basically a textual copy-paste, it's not just unnecessary to include the above header, but it will bloat your binary size without any reason.Include what you need and that is
<algorithm>
as Swastik Baranwal pointed out.As the most important reason to use C++ is still performance, I'd be happy to see a comparison among the different ways to reverse a string.
Do not use
#include<bits/stdc++.h>
, it only works for UNIX systems. You should strongly prefer to use#include <algorithm>
instead.Not necessary. I've used #include on Windows and it works perfectly fine
What compiler have you used? I think you should read this stackoverflow.com/questions/318160...
IDE: CodeBlocks
Compiler: MS Visual C++.
I have tried #include in vs code and it doesn't work.