Java Program To Reverse Words In String (Reverse only words in input order)

1. Overview


In this tutorial, We'll learn how to reverse the words in a string in java. The solution to this problem can be done using the StringBuilder class and using java 8 stream concepts. Many developers will be confused about whether word order needs to be reversed or each word should be reversed. You should clear on this with the interviewer. This will give a hint to the interviewer that the candidate is thinking and coming with a questionnaire.

But in this article, we will be reversing each word as it appears the order in the input as below.

Example:

String input = "Welcome to the JavaProgramTo.com blog"

Output:

emocleW ot eht moc.oTmargorPavaJ golb 

We recommend trying to solve the problem without seeing the answers. Once you come up with your own algorithm then see the different answers.

Java Program To Reverse Words In String (Reverse only words in input order)




2. Using StringBuilder and String split() method


In this approach, we will be using the String split(), charAt(), length() and StringBuilder class append append() methods.

A) First split the given string by whitespace.
B) Take the first word and reverse it. Finally, add the reversed word to the new StringBuilder. Append the white space at the end of each word.
C) Repeat step B for all words.
D) Finally, covert StringBuilder into String using the toString() method.

package com.java.w3schools.blog.java.program.to.strings;

/**
*
* Reversing each word in string without loosing its initial order of the words.
*
* @author javaprogramto.com
*
*/
public class ReverseWordsStringBuilder {

private static final String WHITESPACE_DELIMITER = " ";

public static void main(String[] args) {

System.out.println("Examples to reversing each word in a string inplace.");
String input1 = "Welcome to the JavaProgramTo.com blog";
String output1 = reverseWordsWithStringBuilder(input1);
System.out.println(" input 1 : " + input1);
System.out.println(" output 1 : " + output1);

String input2 = "This is part of String interview programs";
String output2 = reverseWordsWithStringBuilder(input2);
System.out.println(" input 2 : " + input2);
System.out.println(" output 2 : " + output2);
}

public static String reverseWordsWithStringBuilder(String input) {

StringBuilder reversedFinalOutput = new StringBuilder();

// splitting the input string by space.
String[] words = input.split(WHITESPACE_DELIMITER);


for (String word : words) {

StringBuilder reversedWord = new StringBuilder();
for (int i = word.length() - 1; i >= 0; i--) {
reversedWord.append(word.charAt(i));
}

reversedFinalOutput.append(reversedWord).append(WHITESPACE_DELIMITER);

// to clear the builder obj.
//reversedWord.setLength(0);
}

String finalOutputStr = reversedFinalOutput.toString();

return finalOutputStr;
}

}

Output:

Examples to reversing each word in a string inplace.

input 1 : Welcome to the JavaProgramTo.com blog
output 1 : emocleW ot eht moc.oTmargorPavaJ golb

input 2 : This is part of String interview programs
output 2 : sihT si trap fo gnirtS weivretni smargorp


3. Using Java 8 Functional Programming


Java 8 Stream api have come up with the new methods that follow functional programming. Now, let us see how we can reverse each word in the string without changing the order of the words.

Pattern class introduced with a stream method splitAsStream() which returns a Stream of Strings. Next, use the map() method to do reverse the string using StringBuilder.reverse() method. Finally, invoke the Collectors.joining(" ") which will collect all strings from the map() method and concatenate them with empty space " " by each word.


Java 8 map() examples

Let us take a look at the Java 8 example program.

First, need to create a Pattern instance to identify the empty space using a regular expression.

This has mainly three steps.

A) Converting input string into the stream.
B) Reversing each word.
C) Merging all reversed words with empty space " "

package com.java.w3schools.blog.java.program.to.strings;

import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
*
* Reversing each word in string without loosing its initial order of the words
* using java 8 stream with functional style.
*
* @author javaprogramto.com
*
*/
public class ReverseWordsJava8Streams {

// pattern matches to the given delimiter (" ")
private static final Pattern pattern = Pattern.compile(" +");

public static void main(String[] args) {

System.out.println("Java 8 program : ");
String input1 = "java pattern and stream api";
String output1 = reverseWordsWithStringBuilder(input1);
System.out.println(" output 1 : " + output1);

String input2 = "reversing using java 8 streams";
String output2 = reverseWordsWithStringBuilder(input2);
System.out.println(" output 2 : " + output2);

}

public static String reverseWordsWithStringBuilder(String input) {

// step 1: converting input string into stream.
Stream<String> stream = pattern.splitAsStream(input);

// step 2: reversing each word.
Stream<StringBuilder> intermeidateOutput = stream.map(word -> new StringBuilder(word).reverse());

// step 3: merging all reversed words with empty space " "
String reversedInput = intermeidateOutput.collect(Collectors.joining(" "));

return reversedInput;
}

}

Output:

Java 8 program : 
output 1 : avaj nrettap dna maerts ipa
output 2 : gnisrever gnisu avaj 8 smaerts

4. Possible Exceptions/Errors:


Here are the problems that come across the implementation. These would be useful when you are trying on your own first and not looking at the solutions.


Examples to reversing each word in a string inplace.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:702)
at com.java.w3schools.blog.java.program.to.strings.ReverseWordsStringBuilder.reverseWordsWithStringBuilder(ReverseWordsStringBuilder.java:39)
at com.java.w3schools.blog.java.program.to.strings.ReverseWordsStringBuilder.main(ReverseWordsStringBuilder.java:18)


5. Conclusion


In this article, We've seen how to reverse each word in a string. Example programs are shown using traditional and java 8 functional style programming model.

And also shown the problems faced during the implementation of the programs.

0 Comments