Best practices for reversing a string in JavaScript, C++ & Python
Tags: cpp, javascript, python, strings
Published: 2020-09-11 23:41:41

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?](#string)
* [Reverse a string in JavaScript](#js)
* [Reverse a string in C++](#cpp)
* [Reverse a string in Python](#python)
* [What to learn next](#next)

<br>

<a name="string"></a>

## 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. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/w8l1f9v3h1969yr72hxq.png)

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.

<br>

### 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! 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uxnubg0g6x0mnzxjt4w1.png)

<a name="js"></a>

## 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:

```js
.s.r.j("")
```


Let's take the string `"Hello!"` and reverse it using this formula. Here is a visual representation of the process.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h5mov0x7y4g4hy6ilt6z.png)

<br>

### 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. 


```js
var word = "Hello!";
 
var splitWord = word.split("");
```

We have now created the following array of standalone characters:

```js
['H', 'e', 'l', 'l', 'o', '!']
```

<br>

### Reverse

Now that we have our characters, we want to reverse them. We can use the  `reverse()` method , which reverses an array in place. 

```js
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. 

<br>

### 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.

```js
joinedWords = reverseWord.join("")
```

The final output would be:

```js
!olleH
```

You can put all your methods together on a single line:

```js
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](https://www.educative.io/blog/reverse-string-javascript-cpp-python), which has a built-in code widget. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0dhjlly3q1bydqgx9z0f.png)

<a name="cpp"></a>

## 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. 

<br>

### 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. 


```cpp
#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. 

```cpp
#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;
}
```


<br>

### 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

```cpp
#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. 
> 
> <b>[Data Structures for Coding Interviews in Python](https://www.educative.io/courses/data-structures-coding-interviews-python) 
> 
> *Also available in [C++](https://www.educative.io/courses/data-structures-coding-interviews-cpp) and [JavaScript](https://www.educative.io/courses/data-structures-coding-interviews-javascript)*</b>


<br>

### 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. 

```cpp
#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;
  
}
```


<br>

### 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.

```cpp
#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](https://www.educative.io/blog/reverse-string-javascript-cpp-python), which has a built-in code widget. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/viotlmuu05z86iu5km2h.png)

<a name="python"></a>

## 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. 

<br>

### 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. 

```py
stringname[stringlength::-1]
```
Or we can write it without specifying the string's length.

```py
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).

```py
str="Hello!" # initial string
stringlength=len(str) # calculate length of the list
slicedString=str[stringlength::-1] # slicing 
print (slicedString) # print the reversed string
```

<br>

### 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]` with `reverseString`
* Decrement the index
* Continue iterating until the index is less than zero

```py
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
```

<br>

### 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:

```py
str="Hello!" 
reversedstring=''.join(reversed(str))
```

Check it out in complete Python code.

```py
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](https://www.educative.io/blog/reverse-string-javascript-cpp-python), which has a built-in code widget. 

<br>

<a name="next"></a>


## 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](https://www.educative.io/courses/data-structures-coding-interviews-javascript)** 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!*

<br>

### Continue reading about data structures and interviews
* [7 JavaScript data structures you must know](https://www.educative.io/blog/javascript-data-structures) 
* [Data Structures 101: implement hash tables in JavaScript](https://www.educative.io/blog/data-strucutres-hash-table-javascript)
* [Ace the top 15 Java algorithm questions for coding interviews
](https://www.educative.io/blog/ace-top-15-java-algorithm-questions)