在 Java 中反转给定的句子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2713655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reverse a given sentence in Java
提问by giri
Can anyone tell me how to write a Java program to reverse a given sentence?
谁能告诉我如何编写 Java 程序来反转给定的句子?
For example, if the input is:
例如,如果输入是:
"This is an interview question"
“这是一道面试题”
The output must be:
输出必须是:
"question interview an is this"
“问题面试是这个”
回答by Oded
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
您将字符串按空格拆分,然后向后迭代以组合相反的句子。
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
回答by Rich Adams
Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.
只需将一个空格字符拆分为一个字符串数组,然后以相反的顺序遍历该数组并构造输出字符串。
String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
output += array[i];
if (i != 0) { output += " "; }
}
回答by Bozho
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
(using ArrayUtils
and StringUtils
from commons-lang, but these are easy methods to write - just a few loops)
(使用ArrayUtils
和StringUtils
来自 commons-lang,但这些是编写的简单方法 - 只需几个循环)
回答by Pops
Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:
Bozho 已经给出了一个很好的特定于 Java 的答案,但是如果您需要在没有 Java API 方法的情况下解决这个问题:
To reverse, you can simply pop individual words onto a stack
and pop them all back off when there are no words left.
要反转,您可以简单地将单个单词弹出到 a 上,stack
并在没有剩余单词时将它们全部弹出。
(Just to be extra clear, Java does provide a Stack
class, so it is possible to use this method in Java as well).
(更明确地说,Java 确实提供了一个Stack
class,因此也可以在 Java 中使用此方法)。
回答by Gareth Davis
a every boring bit of java:
一个无聊的java:
List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
b.append(s).append(' ');
}
b.toString().trim();
in groovy it's a little bit more readable:
在 groovy 中,它更具可读性:
"this is an interview question"
.split("\s")
.reverse()
.join(' ')
回答by polygenelubricants
Just being different: a recursive solution. Doesn't add any extra spaces.
只是与众不同:递归解决方案。不添加任何额外的空格。
public static String reverse(String s) {
int k = s.indexOf(" ");
return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}
System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"
I will also improve on the split
solution by using \b
instead (it's so obvious!).
我还将split
通过使用\b
来改进解决方案(这太明显了!)。
String[] parts = "Word boundary is better than space".split("\b");
StringBuilder sb = new StringBuilder();
for (int i = parts.length; i --> 0 ;) {
sb.append(parts[i]);
}
System.out.println("[" + sb.toString() + "]");
// prints "[space than better is boundary Word]"
回答by Searles
I also give it a try: Here's a version using a stack and a scanner:
我也试一试:这是一个使用堆栈和扫描仪的版本:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
回答by gmhk
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
回答by gammabowl
nicer approach probably.. had seen the logic somewhere..here is my code which might do the job.
可能更好的方法......在某处看到了逻辑......这是我的代码可以完成这项工作。
public class revWords {
public static void main(String[] args) {
revWords obj = new revWords();
String print = obj.reverseWords("I am God");
System.out.println(print);
}
public String reverseWords(String words)
{
if(words == null || words.isEmpty() || !words.contains(" "))
return words;
String reversed = "";
for( String word : words.split(" "))
reversed = word + " " + reversed;
return reversed;
}
}
回答by Rajender Saini
I don't think you should use any library.. 1) Reverse whole string 2) Reverse each word.
我认为您不应该使用任何库。 1) 反转整个字符串 2) 反转每个单词。
public static void revWord(char[] a) {
// reverse whole
revWord(a, 0, a.length);
int st = -1;
int end = -1;
for (int i = 0; i < a.length; i++) {
if (st == -1 && a[i] != ' ') {
st = i;
}
if (end == -1 && a[i] == ' ' ) {
end = i;
}
if(i == a.length-1){
end=i+1;
}
if (st != -1 && end != -1) {
revWord(a, st, end );
st = -1;
end = -1;
}
}
}
public static void revWord(char[] a, int s, int l) {
int mid = (l - s) / 2;
l--;
for (int i = 0; i < mid; i++, l--) {
char t = a[s+i];
a[s+i] = a[l];
a[l] = t;
}
}
`
`