➤ Sum of digits in a String
➤ Count No of Vowels String
➤ String Pattern Programs in Java
➤ Take String Input In Java
➤ Take Multiple String Input in Java
➤ How To Reverse a String In Java
➤ Remove Special Characters
➤ String – Remove Character
➤ String Palindrome In Java
➤ Sort String In Java
➤ How to Compare Strings In Java
➤ Second Occurrence of Character
➤ Replace nth Occurrence String
➤ Last Occurrence of Character
➤ Uppercase & Lowercase
➤ Java Check If Char is Uppercase
➤ Check If String is Uppercase
➤ Swap Characters in String Java
➤ Java String indexOf() Method
➤ How to Replace Dot in Java?
➤ How to Find Length of String
➤ Substring Method In Java
➤ Split Method In Java
Reverse Words In A String Java | Previously we have seen different approaches to reverse a string in Java programming. Now let us see how to reverse words in a string in Java.
In a given sentence or string, the words are separated by whitespaces like tab, space, and e.t.c. To reverse each word in a given string we can take help from the StringBuilder class. The StringBuilder class contains a reverse() method which is used to reverse the given string value.
On reversing the words in a given string, the position of the words won’t be changed instead the position of each character in a word will be changed. Let us understand it through an example. Example:-
String: Hi, How are You?
After reversing the words: ,iH woH era ?uoY
Program to Reverse Words In a String Java
public class Main {
public static String reverseWords(String string) {
String words[] = string.split("\\s");
String reverse = "";
for (String word : words) {
StringBuilder sb = new StringBuilder(word);
sb.reverse();
reverse += sb.toString() + " ";
}
return reverse.trim();
}
public static void main(String[] args) {
String string = "Welcome to Know Program";
System.out.println("String: " + string);
System.out.println("After reversing the words: "
+ reverseWords(string));
}
}
Output:-
String: Welcome to Know Program
After reversing the words: emocleW ot wonK margorP
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!