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 = "w3wiki";
    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 = "w3wiki";
         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 = "w3wiki"
 
    # 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 = "w3wiki";
        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 = "w3wiki";
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 = "w3wiki";
reverseStr($str);
echo $str;
 
// This code is contributed by ajit.
?>


Output

skeegrofskeeg

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

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

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

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

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

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

Table of Content

  • Reverse String using a Loop:
  • Reverse String using inbuilt method
  • Reverse String using Recursion:
  • Reverse String using two pointers:
  • String Reverse String using Stack:

Recommended Problem
Reverse a String
Solve Problem

Similar Reads

Reverse String using a Loop:

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

Reverse String using inbuilt method

...

Reverse String using Recursion:

...

Reverse String using two pointers:

...

String Reverse String using Stack:

...