-4

Reversing the string while maintaining the index of COMMA.

the string that need to be reversed : "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g".

Expected output: "g,od ,yzal ,eht ,revo, spmuj ,xof nw,orb kc,iuq eh,T"

Zafer
  • 1
  • 3
  • 1
    Okay, what you have tried so far ? Apart posting here. – Suresh Atta Jun 02 '14 at 07:22
  • possible duplicate of [Reverse a given sentence in java](http://stackoverflow.com/questions/2713655/reverse-a-given-sentence-in-java) – UmNyobe Jun 02 '14 at 07:33
  • I put the wrong duplicate : – UmNyobe Jun 02 '14 at 07:35
  • what I able to do is reverse the string including the comma,s. class Reverse { public static void main (String [] args){ String phrase = "\"T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g\""; phrase =new StringBuffer(phrase).reverse().toString(); System.out.println("the reversed string :" + phrase); } } But i don't know how to make the comma remain at its place . – Zafer Jun 02 '14 at 08:14

3 Answers3

2

use StringBuffer and Stack first remove all commas and save the index of them on stack after reversing insert commas at location that you saved them on stack. use stringBufferObject.deleteCharAt(index); for deleting a character and use stringBufferObject.reverse(); for reversing string.

Karo
  • 273
  • 4
  • 16
  • +1 Nice answer - enough detail for someone to figure it out, but not a spoon-fed answer. I suspect the OP was hoping for the latter :-) – Duncan Jones Jun 02 '14 at 07:48
-1

Here this is code you can use it

String original =  "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g";

    String reverse = original.replaceAll(",","");
    StringBuilder rev = new StringBuilder(reverse);
    rev = rev.reverse();
    String output="";
    int j = 0;
    for (int i = 0; i < original.length(); i++) {
        if(original.charAt(i) == ','){
            output += ",";
        }else{
            output+=rev.charAt(j++);
        }
    }

     System.out.println(output);
Saeed Perfect
  • 47
  • 1
  • 10
-1

Here is the code with your input

public class Test {
    public static void main(String [] args){
        String original =  "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g";

         String reverse = "";
          int length = original.length();

          for ( int i = length - 1 ; i >= 0 ; i-- )
             reverse = reverse + original.charAt(i);

          System.out.println("Reverse of entered string is: "+reverse);
    }
}
user243405
  • 83
  • 7