Does the reverse word string in Java give the wrong result?

Here is my code for printing string characters turned upside down in Java without using any API. But it does not work properly. Can someone help me fix this?

public static void main(String args[]) { String input = "I am test"; String result = ""; for (int i = input.length() - 1; i > 0; i--) { Character c = input.charAt(i); if (c != ' ') { result = c + result; } else { System.out.println(result + " "); } } } 

It gives the output "test amtest", and the output should be "test am I".

Please help me get the exact result without using predefined methods or APIs.

+8
java string reverse
source share
5 answers

There are four problems in your implementation:

  • You don't go to zero
  • You put the end of the line after each printout in a loop,
  • You do not print the result of the tail after the loop is completed and
  • You do not clear result after printing in a loop.

Solving these problems will give you the correct result ( demo ).

+14
source share

to try

 public static void main(String args[]) { String input = "I am test"; String result = ""; int start=input.length()-1; for (int i = input.length()-1; i >=0; i--) { Character c = input.charAt(i); if (c == ' ') { for(int j=i+1;j<=start;j++) result +=input.charAt(j); result+=" "; start=i-1; } else if (i==0) { for(int j=0;j<=start;j++) result +=input.charAt(j); } } System.out.println(result); }//It is giving output as test amtest //output should be : test am I 
+4
source share
 public static void main(String args[]) { String input = "I am test"; String result = ""; String[] frags = input.split(" "); for (int i = frags.length - 1; i >= 0; i--) { System.out.print(frags[i] + " "); } System.out.println(); } 
+4
source share

You can also try recursion -

 public static void main(String args[]) { String input = "I am test"; List<String> listOfString = Arrays.asList(input.split(" ")); System.out.println(reverseString(listOfString)); } private static String reverseString(List<String> input) { int n = input.size(); String result = ""; if(input.isEmpty()){ return result; } if(n>1){ /*adding last element with space and changes the size of list as well test + " " + [am, I] test + " " + am + " " + [I]*/ result = input.get(n-1) + " " + reverseString(input.subList(0, n-1)); }else{ result = input.get(n-1); } return result; } 

hope this helps.

+1
source share
 public static void main(String args[]){ String input = "I am test"; String result=""; for(int i=input.length()-1;i>=0;i--){ result=result+input.charAt(i); } System.out.println(result); } 
-one
source share

All Articles