Reverse individual words | Java program to reverse individual words in a given string using STL list ; reverses individual words of a string ; Traverse given string and push all characters to stack until we see a space . ; When we see a space , we print contents of stack . ; Since there may not be space after last word . ; Driver program to test above function
import java . io . * ; import java . util . * ; class GFG { static void reverseWords ( String str ) { Stack < Character > st = new Stack < Character > ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { if ( str . charAt ( i ) != ' ▁ ' ) st . push ( str . charAt ( i ) ) ; else { while ( st . empty ( ) == false ) { System . out . print ( st . pop ( ) ) ; } System . out . print ( " ▁ " ) ; } } while ( st . empty ( ) == false ) { System . out . print ( st . pop ( ) ) ; } } public static void main ( String [ ] args ) { String str = " Geeks ▁ for ▁ Geeks " ; reverseWords ( str ) ; } }