A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java/string/reverse-words-in-string/ below:

Reverse Words in String without Changing Order

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:

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 !!

Sourcecode on Github


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4