Skip to Content

Reverse string by word using StringTokenizer example

  1. /*
  2.         Reverse string by word using StringTokenizer example.
  3.         This example shows how to reverse a line or sentense using
  4.         Java StringTokenizer and String classes.
  5. */
  6.  
  7. import java.util.StringTokenizer;
  8.  
  9. public class ReverseLine {
  10.  
  11.         public static void main(String[] args) {
  12.                
  13.                 String strLine = "Java Reverse string by word example";
  14.                
  15.                 //specify delimiter as " " space
  16.                 StringTokenizer st = new StringTokenizer(strLine, " ");
  17.                
  18.                 String strReversedLine = "";
  19.                
  20.                 while(st.hasMoreTokens())
  21.                 {
  22.                         strReversedLine = st.nextToken() + " " + strReversedLine;
  23.                 }
  24.                
  25.                 System.out.println("Reversed string by word is : " + strReversedLine);
  26.         }
  27. }
  28.  
  29. /*
  30. Output would be
  31. Reversed string by word is : example word by string Reverse Java  
  32. */