Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a given sentence in Java

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"

like image 386
giri Avatar asked Apr 26 '10 13:04

giri


People also ask

How do you reverse a sentence?

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.


2 Answers

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 "
like image 136
Oded Avatar answered Sep 18 '22 08:09

Oded


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)

like image 32
Bozho Avatar answered Sep 18 '22 08:09

Bozho