In this guide, we will learn how to reverse a String in java word by word. For example: If user enters a string “hello world” then the program should output “world hello”. This can be done by splitting the string into words, reversing the order of words and then joining them back together.
Program to reverse a String word by word
Let’s see the complete program. Here we are using String split() method for splitting the input string into words, then using for loop and append()
method to join them back together after reversing the order.
public class ReverseWords {
public static void main(String[] args) {
String input = "Hello readers this is a Java Program";
String reversed = reverseWords(input);
System.out.println("Original: " + input);
System.out.println("Reversed: " + reversed);
}
public static String reverseWords(String str) {
// Split the string into words
String[] words = str.split(" ");
// Reverse the order of the words
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]);
if (i != 0) {
reversedString.append(" ");
}
}
return reversedString.toString();
}
}
Output
Original: Hello readers this is a Java Program
Reversed: Program Java a is this readers Hello
Points to Note:
1. Multiple Spaces: If there are multiple spaces between words or before or after string then you must take care of that by trimming extra spaces. Refer: How to remove trailing spaces from a string
public class ReverseWords {
public static void main(String[] args) {
String input = " Hello readers this is Java ";
String reversed = reverseWords(input);
System.out.println("Original: \"" + input + "\"");
System.out.println("Reversed: \"" + reversed + "\"");
}
public static String reverseWords(String str) {
// Trimming the leading and trailing spaces
str = str.trim();
// This split handles multiple spaces. Use this regex.
String[] words = str.split("\\s+");
// Reverse the order of the words
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]);
if (i != 0) {
reversedString.append(" ");
}
}
return reversedString.toString();
}
}
Output:
Original: " Hello readers this is Java "
Reversed: "Java is this readers Hello"
2. Empty Strings: If you are taking input from the user, you should also check whether the input string is empty or not before passing the string to reverseWords()
method. Refer: How to check if string is empty, blank or null.
Place the following code in the beginning of reverseWords()
method. This will ensure that when the given string is empty, it returns the string as it is.
// Check if the input string is empty
if (str.isEmpty()) {
return str;
}
Leave a Reply