简体   繁体   English

使用StringBuffer反转String中单词的代码

[英]Code to reverse words in a String using StringBuffer

This is some code for reversing characters in a string using StringBuffer : 这是使用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 ? 有没有类似的方法来使用StringBuffer反转字符串中的单词?

Input: "I Need It" and Output should be: "It Need I" 输入:“我需要它”,输出应该是:“它需要我”

You may use StringUtils reverseDelimited : 您可以使用StringUtils reverseDelimited

Reverses a String that is delimited by a specific character. 反转由特定字符分隔的String。 The Strings between the delimiters are not reversed. 分隔符之间的字符串不会颠倒。 Thus java.lang.String becomes String.lang.java (if the delimiter is '.'). 因此java.lang.String变为String.lang.java(如果分隔符是'。')。

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 . 您也可以找到一个较为漫长的解决方案,而它在这里

Using only JDK methods 仅使用JDK方法

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 结果是It Need I

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM