本文介绍了用Java反转给定的句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有谁能告诉我如何编写Java程序来反转给定的句子?
Can anyone tell me how to write a Java program to reverse a given sentence?
例如,如果输入是:
输出必须是:
推荐答案
你用空格分割字符串,然后向后迭代它以组合反向句子。
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 "
这篇关于用Java反转给定的句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!