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"
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"
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.
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);
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);
}
}