Reverse the Words of a String using Stack | Java implementation of the above approach ; Function to reverse the words of the given String without using strtok ( ) . ; Create an empty String stack ; Create an empty temporary String ; Traversing the entire String ; Push the temporary variable into the stack ; Assigning temporary variable as empty ; For the last word of the String ; Get the words in reverse order ; Driver code
import java . util . * ; class GFG { static void reverse ( String s ) { Stack < String > stc = new Stack < > ( ) ; String temp = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == ' ▁ ' ) { stc . add ( temp ) ; temp = " " ; } else { temp = temp + s . charAt ( i ) ; } } stc . add ( temp ) ; while ( ! stc . isEmpty ( ) ) { temp = stc . peek ( ) ; System . out . print ( temp + " ▁ " ) ; stc . pop ( ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { String s = " I ▁ Love ▁ To ▁ Code " ; reverse ( s ) ; } }