fork download
  1. import java.io.*;
  2. import java.util.*;
  3. class ReverseStringPreserveSpace {
  4. static void reverseString(String input) {
  5.  
  6. char[] inputArray = input.toCharArray();
  7. char[] result = new char[inputArray.length];
  8.  
  9. for (int i = 0; i < inputArray.length; i++) {
  10. if (inputArray[i] == ' ') {
  11. result[i] = ' ';
  12. }
  13. }
  14.  
  15. int j = result.length - 1;
  16.  
  17. for (int i = 0; i < inputArray.length; i++) {
  18. if (inputArray[i] != ' ') {
  19. if (result[j] == ' ') {
  20. j--;
  21. }
  22. result[j] = inputArray[i];
  23. j--;
  24. }
  25. }
  26. System.out.println(input + " --> " + String.valueOf(result));
  27. }
  28.  
  29. public static void main(String[] args) {
  30. Scanner sc=new Scanner(System.in);
  31. int t=sc.nextInt();
  32. while(t>0){
  33.  
  34. reverseString(sc.nextLine());
  35. t--;
  36. }
  37. }
  38. }
Success #stdin #stdout 0.15s 48108KB
stdin
2
a b c d
String answer
stdout
 --> 
a b c d --> d c b a