regex

Simple string tokenizer

In this example we shall show you how to use a simple StringTokenizer. The string tokenizer class allows an application to break a string into tokens. To use a StringTokenizer one should perform the following steps:

  • Construct a new StringTokenizer for a specified String.
  • Use hasMoreElements() and nextToken() API methods of StringTokenizer to get the tokens from the string tokenizer. The tokenizer uses the default delimiter set, which is ” \t\n\r\f”: the space character, the tab character, the newline character, the carriage-return character and the form-feed character. Delimiter characters themselves will not be treated as tokens.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.Arrays;
import java.util.StringTokenizer;

public class StrTokenizer {

    public static void main(String[] args) {

  

  String str = "But I'm not dead yet! I feel happy!";

  StringTokenizer srtok = new StringTokenizer(str);

  while (srtok.hasMoreElements()) {


System.out.println(srtok.nextToken());

  }

  System.out.println(Arrays.asList(str.split(" ")));
    }
}

Output:

But
I'm
not
dead
yet!
I
feel
happy!
[But, I'm, not, dead, yet!, I, feel, happy!]

 
This was an example of how to use a simple StringTokenizer in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button