how-to

Working with String

How to work with StringTokenizer - how to split string to parts ?

Use this sample use:

import java.util.StringTokenizer;

java.util.StringTokenizer is class for spliting string into parts by delimiter. You can use three variants.

VARIANT 1 - classical delimiters

In this variant you can use classical internal delimiters - " \t\n\r\f". String is splitted by them.

/* -- construct with classical delimiters */
StringTokenizer tokenizer = new StringTokenizer( "This is a text" );

/* -- count of tokens */
System.out.println( "Tokens count:" + tokenizer.countTokens() );

/* -- split it */
while ( tokenizer.hasMoreElements() ) {
  System.out.println( "Token = " + tokenizer.nextElement() );
}
The output will be:
Tokens count:4
Token = This
Token = is
Token = a
Token = text

VARIANT 2 - users delimiters

Now you can define your own list of delimiters.

/* -- construct with your delimiters */
StringTokenizer tokenizer = new StringTokenizer( "2012-06/05", "-/" );

/* -- count of tokens */
System.out.println( "Tokens count:" + tokenizer.countTokens() );

/* -- split it */
while ( tokenizer.hasMoreElements() ) {
  System.out.println( "Token = " + tokenizer.nextElement() );
}
The output will be:
Tokens count:3
Token = 2012
Token = 06
Token = 05

VARIANT 3 - users delimiters with returning delimiter as token

Now you can define your own list of delimiters. Last parameter is this constructor ensure returning delimiter as a token too.

/* -- construct with your delimiters */
StringTokenizer tokenizer = new StringTokenizer( "2012-06/05", "-/", true );

/* -- count of tokens */
System.out.println( "Tokens count:" + tokenizer.countTokens() );

/* -- split it */
while ( tokenizer.hasMoreElements() ) {
  System.out.println( "Token = " + tokenizer.nextElement() );
}
The output will be:
Tokens count:5
Token = 2012
Token = -
Token = 06
Token = /
Token = 05