Word Reverse Program
How To Reverse The Order Of Words In A Given Input String.
Input:
"My name is Darga "
Output:
"Darga is name My"
package praticeprogrms2;
public class WordReverse
{
public static void main(String[] args)
{
String input = "My name is Darga";
String output = reverseWords(input);
System.out.println("Input : " +input);
System.out.println("Output : " +output);
}
public static String
reverseWords(String input)
{
String[] words = input.split(" "); // Split the
input string into words
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--)
{
reversed.append(words[i]).append(" "); // Append words
in reverse order
}
return reversed.toString().trim();
// Remove the trailing space and return the result
}
}
Output :
Input : My name is Darga
Output : Darga is name My
Explanation:
- The reverseWords function takes the input string as a parameter.
- It uses the split method to break the input string into an array of words, splitting at each space.
- A StringBuilder named reversed is used to build the reversed word order.
- A loop runs through the array of words in reverse order (from the last word to the first).
- Each word is appended to the reversed StringBuilder, followed by a space.
- Finally, the trim method is called to remove the trailing space, and the reversed string is returned.
Comments
Post a Comment