This is the Java Program to Reverse a String Word by Word in Place
Given a string, reverse each word in its place, where words are separated by whitespace.
Example:
String x = “We belong to Russia”
Output = “eW gnoleb ot aissuR”
Split the given string into various substrings, whenever space is encountered. Reverse each substring and create a new string from the reversed substrings.
Here is the source code of the Java Program to Reverse a String Word by Word in Place. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Reverse a String Word by Word in Place.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ReverseWordsInPlace {
// Function to reverse the string
static String reverseString(String str) {
String[] words = str.split(" ");
String rev = "";
int i, j;
for (i = 0; i < words.length; i++) {
StringBuffer sb = new StringBuffer(words[i]);
rev+=sb.reverse().toString();
rev+=" ";
}
return rev;
}
// Function to read the input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the text string");
String str;
try{
str=br.readLine();
}
catch(Exception e){
System.out.println("Error reading input");
return;
}
String rev = reverseString(str);
System.out.println("The reverse of the string word by word in place is\n");
System.out.println(rev);
}
}
1. In function reverseString(), the string str is split into various tokens using split function and the resulting array of tokens is stored in variable words.
2. The loop for (i = 0; i < words.length; i++) traverses through the words array.
3. The nested loop for (j = words[i].length() – 1; j >= 0; j–) traverses the various words in reverse order, adding each character to the rev string.
4. Finally the rev string is displayed.
Time Complexity: O(n) where n is the length of the string.
Case 1 (Simple Test Case): Enter the text string We belong to Russia The reverse of the string word by word in place is eW gnoleb ot aissuR Case 2 (Simple Test Case - another example): Enter the text string Hello I am Jane The reverse of the string word by word in place is olleH I ma enaJ
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Information Technology MCQs
- Check Java Books
- Apply for Computer Science Internship
- Apply for Java Internship
- Check Programming Books