2

How to reverse String in place in Java

input String : 1234 Output Should : 4321

what i have tried.

public static void main(String args[]) 
{ 
 String number = "1234"; 
 System.out.println("original String: " + number); String reversed = inPlaceReverse(number);
 System.out.println("reversed String: " + reversed);
}



public static String inPlaceReverse(final String input) 
{
   final StringBuilder builder = new StringBuilder(input); 
   int length = builder.length();
   for (int i = 0; i < length / 2; i++)
   {
      final char current = builder.charAt(i); 
      final int otherEnd = length - i - 1;
      builder.setCharAt(i, builder.charAt(otherEnd)); // swap 
      builder.setCharAt(otherEnd, current); 
   }
 return builder.toString(); 
}

i am getting answer like: reversed String: 4231 as i expected 4321.

Vikas Suryawanshi
  • 522
  • 1
  • 5
  • 12

8 Answers8

6

If your teacher wants to see your work then you should manipulate the chars directly. Something like the following should be enough to let you spot the mistake:

public static String reverse(String orig)
{
    char[] s = orig.toCharArray();
    final int n = s.length;
    final int halfLength = n / 2;
    for (int i=0; i<halfLength; i++)
    {
        char temp = s[i];
        s[i] = s[n-1-i];
        s[n-1-i] = temp;
    }
    return new String(s);
}
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
1

It can be even simpler using StringBuilder's reverse() function:

public static String inPlaceReverse(String input) {
   StringBuilder builder = new StringBuilder(input); 
   return builder.reverse().toString();
}
Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • 2
    hehe, he won't get marks for using such API. I think the teacher wanted "showing your work" :) – Minh Kieu Jun 09 '17 at 08:20
  • @MinhKieu Yeah, maybe. Let's say this is the *without reinventing the wheel* answer, for further readers ;P – Mistalis Jun 09 '17 at 08:22
  • @Mistalis - I wonder why the StringBuilder class provides such a function but String does not. Either there is a good reason, or the developers of StringBuilder did too many coding interview questions :P – MasterJoe Apr 29 '20 at 00:02
0
public static String inPlaceReverse(String number) {
        char[] ch = number.toCharArray();
        int i = 0;
        int j = number.length()-1;
        while (i < j) {
            char temp = ch[i];
            ch[i] = ch[j];
            ch[j] = temp;
            i++;
            j--;
        }
        return String.valueOf(ch);
    }
gati sahu
  • 2,576
  • 2
  • 10
  • 16
0

1. Using Character Array:

public String reverseSting(String inputString) {
    char[] inputStringArray = inputString.toCharArray();
    String reverseString = "";
    for (int i = inputStringArray.length - 1; i >= 0; i--) {
        reverseString += inputStringArray[i];
    }
    return reverseString;
}

2. Using StringBuilder:

public String reverseSting(String inputString) {
    StringBuilder stringBuilder = new StringBuilder(inputString);
    stringBuilder = stringBuilder.reverse();
    return stringBuilder.toString();
}

OR

return new StringBuilder(inputString).reverse().toString();
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
0

This is an interview question. Reverse a String in place :

public class Solution4 {
    public static void main(String[] args) {

        String a = "Protijayi";

        System.out.println(reverse(a)); //iyajitorP
    }

    private static String reverse(String a) {
           char[] ca = a.toCharArray();
           int start = 0 ; int end = a.length()-1;
           while(end > start) {
               swap(ca,start,end);
               start++;
               end--;
           }//while

        return new String(ca);
    }

    private static void swap(char[] ca, int start, int end) {
        char t = ca[start];
        ca[start] = ca[end];
        ca[end] = t ;
        }
}
Soudipta Dutta
  • 1,353
  • 1
  • 12
  • 7
0

Mind also, that you can avoid using additional memory during the swap, though having some extra computation.

public class StringReverser {

public static String reverseStringInPlace(String toReverse) {

    char[] chars = toReverse.toCharArray();

    int inputStringLength = toReverse.length();

    for (int i = 0; i < inputStringLength / 2; i++) {
        int toMoveBack = toReverse.charAt(i);
        int toMoveForward = toReverse.charAt(inputStringLength - i - 1);

        //swap
        toMoveForward = toMoveBack - toMoveForward;
        toMoveBack -= toMoveForward;
        toMoveForward += toMoveBack;

        chars[i] = (char) toMoveBack;
        chars[inputStringLength - i - 1] = (char) toMoveForward;
    }

    return String.valueOf(chars);

}

public static void main(String[] args) {

    System.out.println(reverseStringInPlace("asd0")); // output: 0dsa
    System.out.println(reverseStringInPlace("sd0")); // output: 0ds
    System.out.println(reverseStringInPlace("")); // output: empty
    System.out.println(reverseStringInPlace("-")); // output: -
    System.out.println(reverseStringInPlace("ABD+C")); // output: C+DBA
    System.out.println(reverseStringInPlace("勒")); // output: 勒
    System.out.println(reverseStringInPlace("分歧。")); // output: 。歧分
    System.out.println(reverseStringInPlace("Marítimo")); // output: omitíraM
} 
}

Relevant to swap discussion can be found here: How to swap two numbers without using temp variables or arithmetic operations?

Yauhen
  • 2,435
  • 1
  • 17
  • 18
0

Convert the string to a character array first and then use recursion.

public void reverseString(char[] s) {
    helper(0, s.length - 1, s);
}

private void helper(int left, int right, char[] s){
    if(left >= right) {
        return;
    }

    char temp = s[left];
    s[left++] = s[right];
    s[right--] = temp;
    helper(left, right, s);
}

So with the input [1,2,3,4], the helper function will be called as follows :

1. helper(0, 3, [1,2,3,4]), Swap 1 and 4
2. helper(1, 2, [1,2,3,4]), Swap 2 and 3
3. helper(2, 1, [1,2,3,4]) Terminates, left is now greater than right
Joseph
  • 5,793
  • 4
  • 34
  • 41
0

After converting into char array. Just swap the both ends ( first index, last index) and move towards each other(first index to last index and from last index to first) until the crossing.

 public void reverseString(char[] s) {
        
        int start = 0;
        int end = s.length-1;
        char temp = ' ';
        while((start)<(end)){
            temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start++;
            end--;
        }
        
        System.out.println(s);
        
    }
Jimmy
  • 995
  • 9
  • 18