Java Program to reverse words in a given string
Program
import java.util.Scanner;
public class ReverseWordsInString {
public void reverseWords(String string)
{
String str[] = string.split(" ");
String reversedString = "";
for (int i = str.length - 1; i >= 0; i--)
{
reversedString += str[i] + " ";
}
System.out.println("Reverse of the given string is: "+ reversedString);
}
public static void main(String[] args){
ReverseWordsInString reverseWordsInString = new ReverseWordsInString();
Scanner reader = new Scanner(System.in);
System.out.println("Enter a string to reverse: ");
String enteredString = reader.nextLine();
reverseWordsInString.reverseWords(enteredString);
}
}
This program reverses the order of words in a given string by splitting the string into an array of words and concatenating them in reverse order.
Use Case:
This program is helpful in situations where word order needs to be reversed, such as text processing, natural language processing tasks, or formatting outputs.
-
Input:
- The program uses the
Scanner
class to accept a string from the user.
- The program uses the
-
Splitting the String:
string.split(" ")
:- Splits the input string into an array of words based on spaces.
-
Reversing the Words:
- A
for
loop iterates through the array of words from the last index to the first index. - Each word is added to a new string (
reversedString
) with a space.
- A
-
Output:
- The reversed string is printed with the words in reverse order.
-
Example Execution:
- Example Input:
Enter a string to reverse: Hello World from Java
- Process:
- Split the string:
["Hello", "World", "from", "Java"]
. - Reverse and concatenate:
"Java from World Hello "
.
- Split the string:
- Output:
Reverse of the given string is: Java from World Hello
- Example Input:
Key Features:
- String Manipulation:
- Splits the string into words and reverses their order.
- Simple Logic:
- Uses a straightforward loop to reverse the array of words.
- Space Preservation:
- Adds a space after each word in the reversed string.
Output
$ javac ReverseWordsInString.java
$ java ReverseWordsInString
Enter a string to reverse:
oodlescoop tutorials and programs
Reverse of the given string is: programs and tutorials oodlescoop