Friday, September 25, 2009

Java - reverse the word order of a sentence

public class Main {
 
    public static void main(String[] args) {
        Words w = new Words();
        String sentence = "The example sentence is here";
        System.out.println(sentence);
        System.out.println("reversed to:");
        System.out.println(w.reverseWordOrderOfSentence(sentence));
    }
}
 
class Words{
    public String reverseWordOrderOfSentence(String sentence){
        // split up by words 
        String[] words = sentence.split(" ");
        sentence = "";
 
        // iterate backward through the array 
        // rebuilding the sentence from the back forward 
        for (int i=words.length; i>0; i--){
            sentence += words[i-1];
            sentence += " ";
        }
        // remove the trailing white space 
        return sentence.trim();
    }
}
 
/* 
 *      OUTPUT: 
        The example sentence is here 
        reversed to: 
        here is sentence example The 
*/ 
 

No comments:

Post a Comment