Reverse the Words of a String using Stack | Java implementation of the approach ; Function to reverse the words of the given sentence ; Create an empty character array stack ; Push words into the stack ; Get the words in reverse order ; Driver code
import java . util . Arrays ; import java . util . Stack ; class GFG { static void reverse ( String k ) { Stack < String > s = new Stack < > ( ) ; String [ ] token = k . split ( " ▁ " ) ; for ( int i = 0 ; i < token . length ; i ++ ) { s . push ( token [ i ] ) ; } while ( ! s . empty ( ) ) { System . out . print ( s . peek ( ) + " ▁ " ) ; s . pop ( ) ; } } public static void main ( String [ ] args ) { String k = " geeks ▁ for ▁ geeks " ; reverse ( k ) ; } }