Easiest Way to Reverse a String
Last Updated :
05 Feb, 2024
Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string.
What is a reversal of string:
Reversing a string is the technique that reverses or changes the order of a given string so that the last character of the string becomes the first character , second last becomes second character of the string and so on.
Examples:
Input: "ABC"
Output: "CBA"
Input: "geeksforgeeks"
Output: "skeegrofskeeg"
The easiest way to reverse a string:
The easiest way to reverse a string is to use the inbuilt function of respective languages. There is a direct function in the “algorithm” header file for doing reverse that saves our time when programming.
// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin, BidirectionalIterator end);
What is reverse() function in C++:
reverse() is a predefined function in the header file algorithm. It is defined as a template in the above-mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n).
Note: The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
Syntax:
void reverse(BidirectionalIterator first, BidirectionalIterator last)
Explanation:
BidirectionalIterator is an iterator that can be used to access any
elements of a container in both forward and backward direction.
Built in reverse() method of the StringBuilder class in Java:
- String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index.
Below is the Implementation of the above approach:
C++
// C++ program to illustrate the
// reversing of a string using
// reverse() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "geeksforgeeks";
// Reverse str[begin..end]
reverse(str.begin(), str.end());
cout << str;
return 0;
}
Java
// Java program to ReverseString using StringBuilder
import java.io.*;
import java.lang.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "geeksforgeeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1.reverse();
// print reversed String
System.out.println(input1);
}
}
Python3
# Python program to reverse a string
def reverse_string(string):
return string[::-1]
str = "geeksforgeeks"
reversed_str = reverse_string(str)
print(reversed_str)
# This code is contributed by Sakshi
C#
using System;
using System.Text;
class ReverseString
{
public static void Main(string[] args)
{
string input = "geeksforgeeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.Append(input);
// reverse StringBuilder input1
input1 = ReverseStringBuilder(input1);
// print reversed String
Console.WriteLine(input1);
}
// Method to reverse a StringBuilder
public static StringBuilder ReverseStringBuilder(StringBuilder sb)
{
char[] arr = sb.ToString().ToCharArray();
Array.Reverse(arr);
return new StringBuilder(new string(arr));
}
}
JavaScript
// JavaScript program to reverse a string using StringBuilder
// Function to reverse a string
function reverseString(str) {
// Create a StringBuilder equivalent in JavaScript
let input1 = new StringBuilder();
// Append the input string to the StringBuilder
input1.append(str);
// Reverse the StringBuilder
input1.reverse();
// Return the reversed string
return input1.toString();
}
// Class equivalent to StringBuilder in JavaScript
class StringBuilder {
constructor() {
this.strings = [];
}
// Append a string to the StringBuilder
append(str) {
this.strings.push(str);
}
// Reverse the StringBuilder
reverse() {
this.strings = this.strings.join('').split('').reverse();
}
// Convert the StringBuilder to a string
toString() {
return this.strings.join('');
}
}
// Main function
function main() {
// Input string
let input = "geeksforgeeks";
// Call the reverseString function
let reversedString = reverseString(input);
// Print the reversed string
console.log(reversedString);
}
// Call the main function
main();
Complexity Analysis:
Time Complexity: O(N), N is the size of the string.
Auxiliary Space: O(1)
Similar Reads
Reverse a String â Complete Tutorial Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.Examples:Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G mo
13 min read
Reverse words in a string Given a string str, your task is to reverse the order of the words in the given string. Note that str may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words.Examples:Input: str = "i.like.this.p
11 min read
Reverse vowels in a given string Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.Examples:Input: "geeksforgeeks"Output: "geeksforgeeks"Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".Input: "helloworld"Output: "hollowerld"Explan
9 min read
How to reverse a String in Python Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works:Using string slicingThis slicing method is one of the s
4 min read
Different Methods to Reverse a String in C++ Reversing the string means the last character will be the first character, second last character will be second character and so on. In C++, we can reverse a string in various different ways as show below:Table of ContentUsing reverse() FunctionUsing Reverse IteratorsUsing a StackUsing Two Pointer T
3 min read
Javascript Program To Reverse Words In A Given String Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples:Â Input: s = "geeks quiz practice code"Â Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice"Â Output: s = "pra
4 min read
Perfect reversible string You are given a string 'str', the task is to check the reverses of all possible substrings of 'str' are present in 'str' or not. Examples: Input : str = "ab" Output: "NO" // all substrings are "a","b","ab" but reverse // of "ab" is not present in str Input : str = "aba" Output: "YES" Input : str = "
6 min read
Print words of a string in reverse order Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simp
10 min read
Add index to characters and reverse the string Given a string str, the task is to encrypt and reverse the string. The string is encrypted by adding every character of the string with it's index in the string i.e. if character'a' is at index 2 then the character in the updated string will be 'a' + 2 = 'c'. Since value of string may go beyond 256,
4 min read
Reverse Words in a Given String in Python In this article, we explore various ways to reverse the words in a string using Python. From simple built-in methods to advanced techniques like recursion and stacks. We are going to see various techniques to reverse a string.Using split() and join()Using split() and join() is the most common method
2 min read