In this java program going to reverse the every words of string and display the reversed string as an output. We can reverse each word of a string by the help of split() and charAt() methods.
Example: Program to reverse every word in a String
public class StringWordReverse
{
public void wordReverse(String str)
{
/* The split() method is used to splits a string in several strings based on the delimiter */
String[] words = str.split(" ");
String reverseStr = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
/* charAt() method returns a char value at the given index number */
reverseWord = reverseWord + word.charAt(j);
}
reverseStr = reverseStr + reverseWord + " ";
}
System.out.println(str);
System.out.println(reverseStr);
}
public static void main(String[] args)
{
StringWordReverse obj = new StringWordReverse();
obj.wordReverse("This is Java World");
obj.wordReverse("Java is platform independent");
}
}
Output:-
