Java Program to reverse a string "WORD BY WORD".
Objective
Write a Java program to reverse every individual word within a string while keeping their original sentence positions.
Algorithm / Approach
- Read a sentence from the user.
- Split the sentence into an array of words using
split(" "). - Initialize an empty accumulator string
s2 = "". - Loop through the array of words.
- Pass each individual word to the
reverse()method. - Append the reversed word and a space to
s2. - Print the final sentence.
Test.java
import java.util.Scanner;
class Test {
public String reverse(String x) {
String rev = "";
for(int i=x.length()-1; i>=0;i--) {
rev = rev + x.charAt(i);
}
return rev;
}
public static void main(String[] a)
{
Test t = new Test();
Scanner s=new Scanner(System.in);
System.out.print("Enter String: ");
String s1 = s.nextLine();
String[] x = s1.split(" ");
String s2="";
for(int i=0; i< x.length; i++) {
s2 =s2+ t.reverse(x[i])+" ";
}
System.out.print("Reverse = "+s2);
}
}
Expected Output
Enter String: Java Prowess App Reverse = avaJ sseworP ppA
Explanation of the Program
- This program tackles a common interview question: reversing the characters of each word without reversing the order of the words themselves.
- The
split(" ")method is incredibly powerful. It breaks the single long sentence string into an array of individual word strings, using the space character as the delimiter. - Once we have an array of individual words, we simply run our standard reverse loop on each one and glue them back together.
Complexity
Time Complexity
O(n) - Where n is the total number of characters in the sentence.
Space Complexity
O(n)