Reverse words in string Java

PROGRAM TO REVERSE THE STRING BY CONSIDERING EACH WORD OF THE STRING



import java.util.*;
class MAIN {
  
    // Function to reverse the words
    // of a given String
    static void printRev(String str)
    {
        // Stack to store each
        // word of the String
        Stack<String> st = new Stack<String>();
  
        // Store the whole String
        // in String stream
        String[] ss = str.split(" ");
  
        for (String temp : ss) 
        {
  
            // Push each word of the
            // String into the stack
            st.add(temp);
        }
  
        // Print the String in reverse
        // order of the words
        while (!st.isEmpty()) 
        {
            System.out.print(st.peek() + " ");
            st.pop();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String str;
        str = "quiz practice code";
        printRev(str);
    }
}

OUTPUT
code practice quiz

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java