谁能告诉我如何编写 Java 程序来反转给定的句子?
例如,如果输入是:
"This is an interview question"
输出必须是:
"question interview an is this"
最佳答案
您将字符串按空格分开,然后向后遍历它以组装颠倒的句子。
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 - 在 Java 中反转给定的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713655/