Can anyone tell me how to write a Java program to reverse a given sentence?
For example, if the input is:
"This is an interview question"
The output must be:
"question interview an is this"
How to use Reverse in a sentence. If only she could reverse this day and start over. After another reverse on the east side of the Gulf of Darien Ojeda returned to Hispaniola and died there. The reverse is true as well.
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 "
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With