在 Java 中反转给定的句子

2022-09-03 16:18:44

谁能告诉我如何编写一个Java程序来反转给定的句子?

例如,如果输入为:

“这是一个面试问题”

输出必须是:

“问题面试是这样的”


答案 1

您将字符串按空格拆分,然后向后迭代它以组合反转的句子。

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 "

答案 2
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");

(使用ArrayUtils和commons-lang,但这些都是很容易编写的方法 - 只有几个循环)StringUtils