Here is the code to reverse a string in java word by word.
public class ReverseStringWords {
public static void main(String[] args) {
String input = "Hello World Java Example";
String reversedString = reverseWords(input);
System.out.println("Original string: " + input);
System.out.println("Reversed string: " + reversedString);
}
public static String reverseWords(String str) {
String[] words = str.split("\\s+"); // Split the string into words
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]).append(" "); // Append each word in reverse order
}
return reversed.toString().trim(); // Trim to remove trailing space
}
}