There are two problems with your code:
- You have passed
input[i]
to new StringBuilder(...)
whereas input
is not an array.
- You have not reversed the string word-wise at all. There can be many ways to do it. The easiest way is to split the string on whitespace and the store them in an array in the reversed order.
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(reverse("grey fox jumps over dog")));
}
public static String[] reverse(String input) {
String[] words = input.split("\s+");
String[] reversed = new String[words.length];
for (int i = 0; i < words.length; i++) {
reversed[words.length - i - 1] = words[i];
}
return reversed;
}
}
Output:
[dog, over, jumps, fox, grey]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…