Java StringTokenizer class

Introduction

Java StringTokenizer can parse a string with delimiters.

Here is an example that creates a StringTokenizer to parse "key=value" pairs.

A sets of "key=value" pairs are separated by a semicolon.

Full source

// Demonstrate StringTokenizer.
import java.util.StringTokenizer;

public class Main{
  static String in = "title=Java Tutorial;" +
    "author=we;" +
    "publisher=demo2s.com;" +
    "copyright=demo source";

  public static void main(String args[]) {
    StringTokenizer st = new StringTokenizer(in, "=;");

    while(st.hasMoreTokens()) {
      String key = st.nextToken();
      String val = st.nextToken();
      System.out.println(key + "\t" + val);
    }//from  www  .  j a va2s. com
  }
}
import java.util.StringTokenizer;

public class Main {
  public static void main(String[] args) {
    String str = "This is 123 a test from demo2s.com";
    String delimiters = "  ,."; // a space and a comma and dot
    StringTokenizer st = new StringTokenizer(str, delimiters);

    String token = null;/*  w  w  w .  j  ava  2s  .c o m*/
    while (st.hasMoreTokens()) {
      token = st.nextToken();
      System.out.println(token);
    }
  }
}



PreviousNext

Related