Tutorials Hut

Print Words Of String In Reverse Order

In this java program we will develop a solution to print words of string in reverse order.

Java Program To Print Words Of String In Reverse Order

package problems;

public class StringWordsInReverse {
public static String reverseTheWordsSol1(String input) {
    String result = "";
    String arr[] = input.split(" ");
    int i = arr.length -1;
    while(i >=0){
        if(i == arr.length -1)
           result = result + arr[i];
        else
            result = result + " " + arr[i];
        i--;
    }
    return result;
}

public static String reverseTheWordsSol2(String input) {
    int i = input.length() - 1;
    int start, end = i + 1;
    String result = "";
    while (i >= 0) {
        if (input.charAt(i) == ' ') {
            start = i + 1;
            while (start != end)
                result += input.charAt(start++);
            result += ' ';
            end = i;
        }
        i--;
    }

    start = 0;
    while (start != end)
        result += input.charAt(start++);
    return result;
}

public static void main(String[] args) {
    System.out.println("Reversed words in string 'I am Alex' is: "+reverseTheWordsSol1("I am Alex"));
    System.out.println("Reversed words in string 'I am Alex' is: "+reverseTheWordsSol2("I am Alex"));
}
}

Output:

Reversed words in string 'I am Alex' is: Alex am I
Reversed words in string 'I am Alex' is: Alex am I


















  • Leave a Reply

    Your email address will not be published. Required fields are marked *