Learn to reverse the words in a Java String such that each word remains in its order, only the characters in the words are reversed in place using Java 8 Stream API and StringUtils classes.
Original String – “alex brian charles”
Reversed words – “xela nairb selrahc”
1. Using Stream and StringBuilder
The algorithm to reverse each word is simple:
- Tokenize the string using String.split() method.
- Loop through string array using Stream and use StringBuilder.reverse() method to reverse each word.
- Join all reversed words by joining the Stream elements.
String input = "alex brian charles";
String reversed = Arrays.stream(input.split(" "))
.map(word -> new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
System.out.println(reversed);
Program output.
xela nairb selrahc
2. Using StringUtils
The StringUtils class is from the Apache command lang3 library. Its reverseDelimited() API reverses each word and joins the string back with the same delimiter. In our case, we will use a space character as delimiter.
String input = "alex brian charles";
String reversed = StringUtils.reverseDelimited(StringUtils.reverse(input), ' ');
System.out.println(reversed);
Program output.
xela nairb selrahc
In this post, we learned to reverse each word in a sentence in Java.
Happy Learning !!
How can I reverse 2 words in a string? For example reverse “Hi John” to “John Hi”.
// this is a little hard coded, you can’t use StringBuilder for this task
String original = “Hi John”;
String [] split = original.split(” “);
String result = split[1] + ” ” + split[0];
System.out.println(result);
@Rishab
was this question is asked in amazon interview?
How can i reverse word of string without using any inbuilt function?
store it in character array .Overwrite accordance with reversal using INDEX OF CHARACTERS
Here below is your program:-
import java.util.Scanner; public class Reverse { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter the string:"); String s = sc.nextLine(); int l = s.length(); System.out.println("Length="+l); char ch[] = s.toCharArray(); for(int i=l-1; i>=0; i--) { System.out.print(ch[i]); } } }