Master java skills

StringTokenizer Class

StringTokenizer class belongs to java.util package. It is used to break a string into tokens around a delimiter (such as space ” ” or comma etc).

Suppose we want to break down the string ‘Java is a programming language‘ into tokens separated by space, then the entire string will be broken into string tokens as shown below.

StringTokenizer constructors

ConstructorDescription
StringTokenizer(String str)This creates StringTokenizer object with given string
StringTokenizer(String str, String delim)Creates StringTokenizer object with given string and delimiter
StringTokenizer(String str, String delim, boolean returnValue)Creates StringTokenizer object with given string, delimiter and return value.

StringTokenizer Example

package com.javatrainingschool;

import java.util.StringTokenizer;

public class StringTokenizerExample {
	
	public static final String SPACE = " ";
	
	public static void main(String[] args) {
		
		String s = "Learn Java from Java Training School";
		
		StringTokenizer st = new StringTokenizer(s, SPACE);
		
		while(st.hasMoreTokens()) {
			System.out.println(st.nextToken());
		}
	}
}

Output:

nextToken() method with a delimiter example

package com.javatrainingschool;

import java.util.StringTokenizer;

public class StringTokenizerExample {
	
	public static final String COMMA = ",";
	
	public static void main(String[] args) {
		
		String s = "Java,programming,language";
		
		StringTokenizer st = new StringTokenizer(s);
		
		while(st.hasMoreTokens()) {
			System.out.println(st.nextToken(COMMA));
		}

	}
}

Output:

Total no of tokens example

package com.javatrainingschool;

import java.util.StringTokenizer;

public class StringTokenizerExample {
	
	public static final String COMMA = ",";
	
	public static void main(String[] args) {
		
		String s = "Java,programming,language";
		
		StringTokenizer st = new StringTokenizer(s, COMMA);
		
		System.out.println("No of tokens : " + st.countTokens());

	}
}

Output: