Aajan
Aajan

Reputation: 937

Code to reverse words in a String using StringBuffer

This is some code for reversing characters in a string using StringBuffer:

String sh = "ABCDE";
System.out.println(sh + " -> " + new StringBuffer(sh).reverse());

Is there any similar way to reverse words in a string using StringBuffer?

Input: "I Need It" and Output should be: "It Need I"

Upvotes: 1

Views: 657

Answers (2)

Andriy Kryvtsun
Andriy Kryvtsun

Reputation: 3344

Using only JDK methods

String input = "I Need It";

String[] array = input.split(" ");
List<String> list = Arrays.asList(array);
Collections.reverse(list);
String output = String.join(" ", list);

System.out.println(output);

And result is It Need I

Upvotes: 1

Idos
Idos

Reputation: 15320

You may use StringUtils reverseDelimited:

Reverses a String that is delimited by a specific character. The Strings between the delimiters are not reversed. Thus java.lang.String becomes String.lang.java (if the delimiter is '.').

So in your case we will use space as a delimiter:

import org.apache.commons.lang.StringUtils;
String reversed = StringUtils.reverseDelimited(sh, ' ');

You may also find a more lengthy solution without it here.

Upvotes: 2

Related Questions