The Wayback Machine - https://web.archive.org/web/20240905172204/https://www.geeksforgeeks.org/string-reverse/
Open In App

String Reverse in C/C++/Java/Python/JavaScript

Last Updated : 25 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
69.49%
3.6L

String reverse or reverse a string means changing the position of each character of the given string to its opposite position from end, i.e. if a character is at position 1 then its new position will be String.length, similarly if a character is at position 2 then its new position will be String.length – 1, and so on.

String Reverse in C/C++/Java/Python/JavaScript

String Reverse in C/C++/Java/Python/JavaScript

Given a string, write a program to reverse the string.

Input: original_string[] = Geeks
Output: string_reversed[] = skeeG

Input: original_string[] = GeeksForGeeks
Output: string_reversed[] = skeeGroFskeeG

Recommended Problem

Reverse String using a Loop:

  1. Initialize an empty string to store the reversed result.
  2. Iterate through the original string in reverse order.
  3. Append each character to the new string.
  4. The new string is the reversed version of the original string.

Below is the implementation to reverse a string using loop in different programming languages:

C++




#include <iostream>
#include <string>
 
std::string reverseStringLoop(const std::string& inputStr) {
    std::string reversedStr;
    for (int i = inputStr.length() - 1; i >= 0; i--) {
        reversedStr += inputStr[i];
    }
    return reversedStr;
}
 
int main() {
    std::string originalStr = "GeeksforGeeks";
    std::string result = reverseStringLoop(originalStr);
    std::cout << result << std::endl;
    return 0;
}


C




#include <stdio.h>
#include <string.h>
 
void reverseStringLoop(char inputStr[]) {
    int length = strlen(inputStr);
    for (int i = length - 1; i >= 0; i--) {
        printf("%c", inputStr[i]);
    }
    printf("\n");
}
 
int main() {
    char originalStr[] = "GeeksforGeeks";
    reverseStringLoop(originalStr);
    return 0;
}


Java




public class ReverseStringLoop {
    public static String reverseStringLoop(String inputStr) {
        StringBuilder reversedStr = new StringBuilder();
        for (int i = inputStr.length() - 1; i >= 0; i--) {
            reversedStr.append(inputStr.charAt(i));
        }
        return reversedStr.toString();
    }
 
    public static void main(String[] args) {
        String originalStr = "GeeksforGeeks";
        String result = reverseStringLoop(originalStr);
        System.out.println(result);
    }
}


Python3




def reverse_string_loop(input_str):
    reversed_str = ""
    for char in input_str[::-1]:
        reversed_str += char
    return reversed_str
 
# Example usage:
original_str = "GeeksforGeeks"
result = reverse_string_loop(original_str)
print(result)


C#




using System;
 
class Program {
    static string ReverseStringLoop(string inputStr) {
        char[] charArray = inputStr.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
 
    static void Main() {
        string originalStr = "GeeksforGeeks";
        string result = ReverseStringLoop(originalStr);
        Console.WriteLine(result);
    }
}


Javascript




function reverseStringLoop(inputStr) {
    let reversedStr = "";
    for (let i = inputStr.length - 1; i >= 0; i--) {
        reversedStr += inputStr[i];
    }
    return reversedStr;
}
 
// Example usage:
let originalStr = "GeeksforGeeks";
let result = reverseStringLoop(originalStr);
console.log(result);


Output

skeeGrofskeeG

Time Complexity: O(n)
Auxiliary Space: O(n) for storing the reversed string.

Reverse String using inbuilt method

  1. Use the inbuilt reverse() method available for strings.
  2. Convert the string to a list.
  3. Call the reverse() method on the list.
  4. Convert the list back to a string.

Below is the implementation to reverse a string using built-in methods in different programming languages:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string str = "geeksforgeeks"; // Input string
    reverse(str.begin(),str.end()); // Reverse the string
    cout << str << std::endl;
    return 0;
}
 
 
// This code is contributed by prajwalkandekar123.


Java




//Java program to reverse a string using StringBuffer class
 
import java.io.*;
import java.util.*;
 
class GFG {
     
    //Driver Code
    public static void main (String[] args) {
        String str = "geeksforgeeks";//Input String
         
        //Step 1: Initialise an object of StringBuffer class
        StringBuffer sb = new StringBuffer(str);
         
        //Step 2: Invoke the .reverse() method
        sb.reverse();
         
        //Step 3: Convert the StringBuffer to string by using toString() method
        System.out.println(sb.toString());
         
    }
}
 
//This code is contributed by shruti456rawal


Python3




# Driver Code
if __name__ == '__main__':
    str = "geeksforgeeks" # Input String
 
    # Step 1: Initialise an object of StringBuffer class
    sb = str[::-1]
 
    # Step 2: Invoke the .reverse() method (not applicable in Python)
 
    # Step 3: Print the reversed string
    print(sb)


C#




// c# code
 
using System;
 
class Program {
    static void Main(string[] args)
    {
        string str = "geeksforgeeks"; // Input string
        char[] charArray
            = str.ToCharArray(); // Convert string to char
                                 // array
        Array.Reverse(charArray); // Reverse the array
        str = new string(
            charArray); // Convert char array back to string
        Console.WriteLine(
            str); // Output the reversed string
    }
}
// ksam24000


Javascript




let str = "geeksforgeeks"; // Input string
str = str.split('').reverse().join(''); // Reverse the string
console.log(str);
 
// This code is contributed by Prajwal Kandekar


Output

skeegrofskeeg

Time Complexity: O(n)
Auxiliary Space: O(1) in all the programming languages except Java in which it will be, O(n) (The extra space is used to store the StringBuffer string).

Reverse String using Recursion:

The recursive algorithm to reverse a string works by swapping the first and last characters until the middle of the string is reached. This process is performed through recursive calls, where in each call, characters at positions i and n-i-1 are swapped, and i is incremented. This continues until i reaches n/2, and the string is completely reversed.

  1. Define a recursive function that takes a string as input.
  2. If the string is empty or has only one character, return the string as it is the base case.
  3. Otherwise, call the function recursively with the substring excluding the first character.
  4. Append the first character to the result of the recursive call.

Below is the implementation of the above approach:

C++




// Recursive C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to reverse the string
void recursiveReverse(string &str;, int i = 0)
{
    int n = str.length();
    if (i == n / 2)
        return;
  // Swap the i and n-i-1 character
    swap(str[i], str[n - i - 1]);
  // Call Recursive function after incrementing i.
    recursiveReverse(str, i + 1);
}
 
// Driver program
int main()
{
    string str = "geeksforgeeks";
    recursiveReverse(str);
    cout << str;
    return 0;
}


Java




// Recursive Java program to reverse a string
import java.io.*;
class GFG
{
 
  // Recursive function to reverse the string
static void recursiveReverse(char[] str, int i)
{
    int n = str.length;
   
    if (i == n / 2)
        return;
   
  // Swap the i and n-i-1 character
    swap(str,i,n - i - 1);
   
  // Call Recursive function after incrementing i.
    recursiveReverse(str, i + 1);
}
static void swap(char []arr, int i, int j)
{
    char temp= arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}
 
// Driver program
public static void main(String[] args)
{
    char[] str = "geeksforgeeks".toCharArray();
    recursiveReverse(str,0);
    System.out.println(String.valueOf(str));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Recursive Python program to reverse a string
 
def recursiveReverse(str, i = 0):
    n = len(str)
 
    if i == n // 2:
        return
    # Swap the i and n-i-1 character
    str[i], str[n-i-1] = str[n-i-1], str[i]
     
    # Call Recursive function after incrementing i.
    recursiveReverse(str, i+1)
 
if __name__ == "__main__":
    str = "geeksforgeeks"
 
    # converting string to list
    # because strings do not support
    # item assignment
    str = list(str)
    recursiveReverse(str)
 
    # converting list to string
    str = ''.join(str)
    print(str)
 
# This code is contributed by
# sanjeev2552


C#




// Recursive C# program to reverse a string
using System;
 
public class GFG
{
  
static void recursiveReverse(char[] str, int i)
{
    int n = str.Length;
    if (i == n / 2)
        return;
   
  // Swap the i and n-i-1 character
    swap(str,i,n - i - 1);
   
  // Call Recursive function after incrementing i.
    recursiveReverse(str, i + 1);
}
static char[] swap(char []arr, int i, int j)
{
    char temp= arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    return arr;
}
  
// Driver program
public static void Main(String[] args)
{
    char[] str = "geeksforgeeks".ToCharArray();
    recursiveReverse(str,0);
    Console.WriteLine(String.Join("",str));
}
}
// This code is contributed by Princi Singh


Javascript




// Recursive JavaScript function to reverse a string
function recursiveReverse(str, i = 0) {
    const n = str.length;
    if (i >= Math.floor(n / 2))
        return str;
    // Swap the i and n-i-1 characters
    str = str.substring(0, i) + str[n - i - 1] + str.substring(i + 1, n - i - 1) + str[i] + str.substring(n - i);
    // Call Recursive function after incrementing i.
    return recursiveReverse(str, i + 1);
}
 
// Driver program
    let str = "geeksforgeeks";
    str = recursiveReverse(str);
    console.log(str);


PHP




<?php
// A Simple PHP program
// to reverse a string
 
// Function to reverse a string
function reverseStr($str)
{
 
    // print the string
    // from last
    echo strrev($str);
}
 
// Driver Code
$str = "geeksforgeeks";
 
reverseStr($str);
 
// This code is contributed
// by Srathore
?>


Output

skeegrofskeeg

Time Complexity: O(n) where n is length of string
Auxiliary Space: O(n)

Reverse String using two pointers:

The idea is to use two pointers. The left pointer is placed at the beginning of the string and the right pointer is placed at the end of the string. Now swap the characters at left and right pointers, after that left pointer moves forward by 1 step and right pointer moves backward by 1 step. This operation is continued till right pointer is ahead of left pointer.

  1. Initialize two pointers, one at the beginning and the other at the end of the string.
  2. Swap the characters at the pointers.
  3. Move the left pointer to the right and the right pointer to the left.
  4. Repeat steps 2 and 3 until the pointers meet or cross each other.

Below is the implementation of the above approach:

C++




// A Simple Iterative C++ program to reverse
// a string
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
 
    // Swap character starting from two
    // corners
    // i is the left pointer and j is the right pointer
    for (int i = 0, j = n - 1; i < j; i++, j--)
        swap(str[i], str[j]);
}
 
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}


Java




//A Simple Iterative Java program to reverse
//a string
import java.io.*;
class GFG {
 
    //Function to reverse a string
    static void reverseStr(String str)
    {
     int n = str.length();
     char []ch = str.toCharArray();
     char temp;
 
     // Swap character starting from two
     // corners
     // i is the left pointer and j is the right pointer
     for (int i=0, j=n-1; i<j; i++,j--)
     {
         temp = ch[i];
         ch[i] = ch[j];
         ch[j] = temp;
     }
         
      
     System.out.println(ch);
    }
 
    //Driver program
    public static void main(String[] args) {
         
        String str = "geeksforgeeks";
         reverseStr(str);
    }
}
// This code is contributed by Ita_c.


Python3




# A Simple Iterative Python program to
# reverse a string
 
# Function to reverse a string
def reverseStr(str):
    n = len(str)
 
    i, j = 0, n-1
 
    # Swap character starting from
    # two corners
    # i is the left pointer and j is the right pointer
    while i < j:
        str[i], str[j] = str[j], str[i]
 
        i += 1
        j -= 1
 
 
# Driver code
if __name__ == "__main__":
    str = "geeksforgeeks"
 
    # converting string to list
    # because strings do not support
    # item assignment
    str = list(str)
    reverseStr(str)
 
    # converting list to string
    str = ''.join(str)
 
    print(str)
 
# This code is contributed by
# sanjeev2552


C#




// A Simple Iterative C# program 
// to reverse a string
using System;
 
class GFG
{
 
    //Function to reverse a string
    static void reverseStr(String str)
    {
        int n = str.Length;
        char []ch = str.ToCharArray();
        char temp;
 
        // Swap character starting from two
        // corners
        // i is the left pointer and j is the right pointer
        for (int i=0, j=n-1; i<j; i++,j--)
        {
            temp = ch[i];
            ch[i] = ch[j];
            ch[j] = temp;
        }
        Console.WriteLine(ch);
    }
 
    //Driver program
    public static void Main(String[] args)
    {
        String str = "geeksforgeeks";
        reverseStr(str);
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
//A Simple Iterative Javascript program to reverse
//a string
 
//Function to reverse a string
function reverseStr(str)
{
    let n = str.length;
     let ch = str.split("");
     let temp;
  
     // Swap character starting from two
     // corners
     // i is the left pointer and j is the right pointer
     for (let i=0, j=n-1; i<j; i++,j--)
     {
         temp = ch[i];
         ch[i] = ch[j];
         ch[j] = temp;
     }
          
       
     document.write(ch.join("")+"<br>");
}
 
//Driver program
let str = "geeksforgeeks";
reverseStr(str);
 
// This code is contributed by rag2127
</script>


PHP




<?php
// A Simple Iterative PHP
// program to reverse a string
 
// Function to reverse a string
function reverseStr (&$str)
{
    $n = strlen($str);
 
    // Swap character starting
    // from two corners
    for ($i = 0, $j = $n - 1;
         $i < $j; $i++, $j--)
        //swap function
        list($str[$i],
             $str[$j]) = array($str[$j],
                               $str[$i]);
}
 
// Driver Code
$str = "geeksforgeeks";
reverseStr($str);
echo $str;
 
// This code is contributed by ajit.
?>


Output

skeegrofskeeg

Time Complexity: O(n) 
Auxiliary Space: O(1)

String Reverse String using Stack:

  1. Initialize an empty stack.
  2. Push each character of the string onto the stack.
  3. Pop the characters from the stack and append them to a new string.
  4. The new string is the reversed version of the original string.

Below is the implementation of the above approach:

C++




// C++ program to reverse a string using stack
#include <bits/stdc++.h>
using namespace std;
 
void reversebyStack(string &str;)
{
  // To store the characters of original string.
   stack<char> st;
   for (int i=0; i<str.length(); i++)
     // Push the charcters into stack
       st.push(str[i]);
 
   for (int i=0; i<str.length(); i++) {
     // Pop the charcters of stack into the original string.
       str[i] = st.top();
       st.pop();
   }      
}
 
// Driver program
int main()
{
  // Original String
    string str = "geeksforgeeks";
    reversebyStack(str);
    cout << str;
    return 0;
}


Java




// Java program to reverse a string using stack
import java.util.*;
class GFG
{
  public static String reversebyStack(char []str)
 {
   Stack<Character> st = new Stack<>();
   for(int i=0; i<str.length; i++)
     // Push the charcters into stack
        st.push(str[i]);
 
   for (int i=0; i<str.length; i++) {
      // Pop the charcters of stack into the original string.
    str[i] = st.peek();
    st.pop();
   }    
   return String.valueOf(str);// converting character array to string
 }
 
// Driver program
   public static void main(String []args)
   {
      String str = "geeksforgeeks";
      str = reversebyStack(str.toCharArray());// passing character array as parameter
      System.out.println(str);
   }
}
// This code is contributed by Adarsh_Verma


Python3




# Python program to reverse a string using stack
 
def reversebyStack(str):
     
    # using as stack
    stack = []
 
    for i in range(len(str)):
      # Push the charcters into stack
        stack.append(str[i])
     
    for i in range(len(str)):
       # Pop the charcters of stack into the original string.
        str[i] = stack.pop()
 
if __name__ == "__main__":
    str = "geeksforgeeks"
 
    # converting string to list
    # because strings do not support
    # item assignment
    str = list(str)
    reversebyStack(str)
 
    # converting list to string
    str = ''.join(str)
    print(str)
     
# This code is contributed by
# sanjeev2552


C#




// C# program to reverse a string using stack
using System;
using System.Collections.Generic;
 
class GFG
{
    public static String reversebyStack(char []str)
    {
        Stack<char> st = new Stack<char>();
        for(int i = 0; i < str.Length; i++)
          // Push the charcters into stack
            st.Push(str[i]);
 
        for (int i = 0; i < str.Length; i++)
        {
           // Pop the charcters of stack into the original string.
            str[i] = st.Peek();
            st.Pop();
        }
         
        // converting character array to string
        return String.Join("",str);
    }
 
    // Driver program
    public static void Main()
    {
        String str = "geeksforgeeks";
         
        // passing character array as parameter
        str = reversebyStack(str.ToCharArray());
        Console.WriteLine(str);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




// Function to reverse a string using a stack
function reverseByStack(str) {
    // To store the characters of the original string.
    const stack = [];
 
    // Push the characters into the stack.
    for (let i = 0; i < str.length; i++) {
        stack.push(str[i]);
    }
 
    // Pop the characters of the stack and build the reversed string.
    let reversedStr = '';
    while (stack.length > 0) {
        reversedStr += stack.pop();
    }
 
    return reversedStr;
}
 
// Driver program
function main() {
    // Original String
    let str = "geeksforgeeks";
    let reversedStr = reverseByStack(str);
    console.log(reversedStr);
}
 
main();
 
 
// This code is contributed by shivamgupta0987654321


Output

skeegrofskeeg

Time Complexity: O(n) 
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a given string is a Reverse Bitonic String or not
Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order of their ASCII values. Examples: Input: str = "zy
6 min read
Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively. Examples: Input: S = "12333444", X = 5, Y = 4, P = "34"Output: 15Explanation:Bel
11 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
PHP | Reverse a String
PHP serves us with many built-in methods which can be used to manipulate strings. In this article, we will learn about how to reverse a string using various methods available in PHP. Examples: Input : GeeksforGeeks Output : skeeGrofskeeG Input : 12485 Output : 58421 Below we have discussed about three basic and most commonly used methods of reversi
3 min read
Reverse String according to the number of words
Given a string containing a number of words. If the count of words in string is even then reverse its even position's words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order. Examples: Input: Ashish Yadav Abhishek Rajput Sunil Pundir Output: ridnuP tupjaR vadaY Ashish
6 min read
Reverse the Words of a String using Stack
Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = "I Love To Code" Output: Code To Love IInput: str = "data structures and algorithms" Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved
8 min read
Reverse the given string in the range [L, R]
Given a string str, and two integers L and R, the task is to reverse the string in the range [L, R] i.e. str[L...R].Examples: Input: str = "geeksforgeeks", L = 5, R = 7 Output: geeksrofgeeks Reverse the characters in the range str[5...7] = "geeksforgeeks" and the new string will be "geeksrofgeeks" Input: str = "ijklmn", L = 1, R = 2 Output: ikjlmn
4 min read
First substring whose reverse is a word in the string
Given a space-separated string str, the task is to find the first substring whose reverse is a word in the string. All the characters of the string are lowercase English alphabet. The string ends with #. If no such substring is present, return -1 Examples: Input: str = "mango is sweet when nam en tastes it#" Output: man Explanation: Substring "man"
6 min read
Reverse all the word in a String represented as a Linked List
Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-&gt; -&gt;l-&gt;o-&gt;v-&gt;e-&gt; -&gt;G-&gt;e-&gt;e-&gt;k-&gt;s-&gt; -&gt;f-
15 min read
Reverse the substrings of the given String according to the given Array of indices
Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ? length(S), for all i.Examples: Input: S = "abcdef", A[] = {2, 5} Output: baedcf Explanation: Input: S = "abcdefghij", A[] = {2, 5} Output: baedcjihgf Approach: The idea is to use the concept of
10 min read
Count of Reverse Bitonic Substrings in a given String
Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasing Examples: Input: S = "bade"Output: 10Explanation
8 min read
Reverse substrings of given string according to specified array indices
Given string str of length N and an array arr[] of integers, for array element arr[i](1-based indexing), reverse the substring in indices [arr[i], N - arr[i] + 1]. The task is to print the string after every reversal. Examples: Input: str = "GeeksforGeeks", arr[] = {2}Output: GkeeGrofskeesExplanation:For first element of the array is 2:Reverse the
7 min read
Count ways to split a string into two subsets that are reverse of each other
Given a string S consisting of N characters, the task is to find the number of ways to split the string into two subsets such that the first subset is the reverse of the second subset. Examples: Input: S = "cabaacba"Output: 4Explanation:Below are the ways of partitioning the string satisfying the given conditions: Take the characters at the indices
7 min read
Minimum number of adjacent swaps to reverse a String
Given a string s. The task is to minimize the number of adjacent swaps required to reverse the string. Examples: Input: s = "abc"Output: 3Explanation: Follow the operations below to solve the given problem.swap(1, 2)-&gt; "bac"swap(2, 3)-&gt; "bca"swap(1, 2)-&gt; "cba" Input: s = "ba"Output: 1 Approach: This problem can be solved by comparing the g
5 min read
Find all substrings with even 1s whose reverse is also present in given String
Given a binary string str. The task is to find the size of the set(contains unique substrings) of substrings such that if there is a substring(suppose A) of length n with an even number of 1's and also there is another substring (suppose B) of the same length n and even number of 1's and it is reverse of A, then only A would be considered in the se
7 min read
Reverse given range of String for M queries
Given a string S of length N and an array of queries A[] of size M, the task is to find the final string after performing M operations on the string. In each operation reverse a segment of the string S from position (A[i] to N-A[i]+1). Examples: Input: N = 6, S = "abcdef", M = 3, A = {1, 2, 3}Output: "fbdcea"Explanation: After the first operation,
15 min read
Remove Repeating chars and Reverse String until no Repetitions
Given a string S which consists of only lowercase English alphabets, the task is to remove the first repeating character, reverse it, and repeat until there are no repeating characters. Return the final string. Examples: Input: S = "abab"Output: baExplanation: In 1st operation: The first non repeating character is a. After Removing the first charac
10 min read
How to Reverse a String using Stack
Given a string, reverse it using stack. Example: Input: str = "GeeksQuiz"Output: ziuQskeeG Input: str = "abc"Output: cba Recommended PracticeReverse a string using StackTry It! Approach: The idea is to create an empty stack and push all the characters from the string into it. Then pop each character one by one from the stack and put them back into
12 min read
Reverse a string without affecting special characters
Given a string, that contains a special character together with alphabets ('a' to 'z' and 'A' to 'Z'), reverse the string in a way that special characters are not affected. Examples: Input: str = "a,b$c"Output: str = "c,b$a"Explanation: Note that $ and , are not moved anywhere. Only subsequence "abc" is reversed Input: str = "Ab,c,de!$"Output: str
10 min read
Print reverse string after removing vowels
Given a string s, print reverse of string and remove the characters from the reversed string where there are vowels in the original string. Examples: Input : geeksforgeeksOutput : segrfsegExplanation :Reversed string is skeegrofskeeg, removing characters from indexes 1, 2, 6, 9 &amp; 10 (0 based indexing),we get segrfseg .Input :duckOutput :kudA si
13 min read
Print reverse of a string using recursion
Write a recursive function to print the reverse of a given string. Code: C/C++ Code // C++ program to reverse a string using recursion #include &lt;bits/stdc++.h&gt; using namespace std; /* Function to print reverse of the passed string */ void reverse(string str) { if(str.size() == 0) { return; } reverse(str.substr(1)); cout &lt;&lt; str[0]; } /*
9 min read
Reverse string without using any temporary variable
We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable. Examples: Input : str = "abc" Output : str = "cba" Input : str = "GeeksforGeeks" Output : str = "skeeGrofskeeG" If we take a look at program to reverse a string or array, all we need to do is s
4 min read
Reverse a string preserving space positions
Write a program to reverse the given string while preserving the position of spaces. Examples: Input : "abc de" Output : edc ba Input : "intern at geeks" Output : skeegt an retni Input : "Help others" Output : sreh topleH Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Create a string to store results. Mark the
8 min read
Reverse vowels in a given string
Given a string, your task is to reverse only the vowels of string. Examples: Input : hello Output : holle Input : hello world Output : hollo werldRecommended PracticeReversing the vowelsTry It! One simple solution is to store all the vowels while scanning the string and placing the vowels in the reverse order in another iteration of string. Impleme
8 min read
Reverse words in a given String in Java
Let's see an approach to reverse words of a given String in Java without using any of the String library function Examples: Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I" Prerequisite: Regular Expression in Java Java Code // Java Program to reverse a String
3 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 simpler way by using the property of the "%s format sp
10 min read
Easiest Way to Reverse a String
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
4 min read
Reverse the string whenever digit is encountered
Given a string s of length N, the task is to traverse the string and reverse the substring from the start to the next encountered digit. After reversing the substring, update the start index to the character immediately following the digit. Example: Input: s = abc123def456ghiOutput: cba123fed456ihg Input: s = abc156ghiOutput: cba156ihg Approach: Th
4 min read
Article Tags :
Practice Tags :