Skip to Content

Java StringTokenizer - Specify Delimiter example

  1. /*
  2.   Java StringTokenizer - Specify Delimiter example.
  3.   This example shows how a specify a delimiter for StringTokenizer object.
  4.   The default delimiters are
  5.   \t character (tab),
  6.   \n character (new line),
  7.   \r character (carriage return) and
  8.   \f character (form feed).
  9. */
  10.  
  11. import java.util.StringTokenizer;
  12.  
  13. public class StringTokenizerSpecifyDelimiterExample {
  14.  
  15.   public static void main(String[] args) {
  16.    
  17.     /*
  18.      * There are two ways to specify a delimiter for a StringTokenizer object.
  19.      * 1. At the creating time by specifying in the StringTokenizer constructor
  20.      * 2. Specify it in nextToken() method
  21.      */
  22.      
  23.     //1. Using StringTokenizer constructor
  24.     StringTokenizer st1 = new StringTokenizer("Java|StringTokenizer|Example 1", "|");
  25.    
  26.     //iterate through tokens
  27.     while(st1.hasMoreTokens())
  28.       System.out.println(st1.nextToken());
  29.    
  30.     //2. Using nextToken() method. Note that the new delimiter set remains the
  31.     //default after this method call
  32.     StringTokenizer st2 = new StringTokenizer("Java|StringTokenizer|Example 2");
  33.    
  34.     //iterate through tokens
  35.     while(st2.hasMoreTokens())
  36.       System.out.println(st2.nextToken("|"));
  37.  
  38.   }
  39. }
  40.  
  41. /*
  42. Java
  43. StringTokenizer
  44. Example 1
  45. Java
  46. StringTokenizer
  47. Example 2
  48. */