Java StringTokenizer example

In Java, you can StringTokennizer class to split a String into different tokenas by defined delimiter.(space is the default delimiter). Here’re two StringTokennizer examples :

Example 1

Uses StringTokennizer to split a string by “space” and “comma” delimiter, and iterate the StringTokenizer elements and print it out one by one.

package com.mkyong;
 
import java.util.StringTokenizer;
 
public class App {
	public static void main(String[] args) {
 
		String str = "This is String , split by StringTokenizer, created by mkyong";
		StringTokenizer st = new StringTokenizer(str);
 
		System.out.println("---- Split by space ------");
		while (st.hasMoreElements()) {
			System.out.println(st.nextElement());
		}
 
		System.out.println("---- Split by comma ',' ------");
		StringTokenizer st2 = new StringTokenizer(str, ",");
 
		while (st2.hasMoreElements()) {
			System.out.println(st2.nextElement());
		}
	}
}

Output

---- Split by space ------
This
is
String
,
split
by
StringTokenizer,
created
by
mkyong
---- Split by comma ',' ------
This is String 
 split by StringTokenizer
 created by mkyong

Example 2

Read a csv file and use StringTokenizer to split the string by “|” delimiter, and print it out.

File : c:/test.csv

1| 3.29| mkyong
2| 4.345| eclipse
package com.mkyong;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
 
public class ReadFile {
 
	public static void main(String[] args) {
 
	BufferedReader br = null;
 
	try {
 
		String line;
 
		br = new BufferedReader(new FileReader("c:/test.csv"));
 
		while ((line = br.readLine()) != null) {
		   System.out.println(line);
 
		   StringTokenizer stringTokenizer = new StringTokenizer(line, "|");
 
		   while (stringTokenizer.hasMoreElements()) {
 
		    Integer id = Integer.parseInt(stringTokenizer.nextElement().toString());
		    Double price = Double.parseDouble(stringTokenizer.nextElement().toString());
		    String username = stringTokenizer.nextElement().toString();
 
			StringBuilder sb = new StringBuilder();
			sb.append("\nId : " + id);
			sb.append("\nPrice : " + price);
			sb.append("\nUsername : " + username);
			sb.append("\n*******************\n");
 
			System.out.println(sb.toString());
		   }
		}
 
		System.out.println("Done");
 
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			if (br != null)
				br.close();
 
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
 
	}
}

Output

1| 3.29| mkyong
 
Id : 1
Price : 3.29
Username :  mkyong
*******************
 
2| 4.345| eclipse
 
Id : 2
Price : 4.345
Username :  eclipse
*******************
 
Done

Reference

  1. http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • RJ

    how can i get
    “550 5.1.1 The email account that you tried to reach does not exist”

    from

    “550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipient’s email address for typos or unnecessary spaces. Learn more at http://support.google.com/mail/bin/answer.py?answer=6596 m9si12310002oep.43 – gsmtp”

    in java… Can anyone help me out??

  • Shubhrajyoti satpathy

    “my name is shubhrajyoti ” want like
    mY
    naMe
    Is
    shUbhraJyotI

    WHAT WILL BE CODE

  • Tin

    Hi Sir,

    How can I set format it with columns like below

    String1 | String2 | String3
    Value1 | Value2 | Value3
    Valueeeeee | Valueeeeeee | Valueeeee
    eeee1 | eeeee2 | eeee3

    Thanks!

    • Tin

      it should all be align. but will continue to next line the long value just to maintain the alignment of text

  • Mohd Asad Khan

    Thank Sir
    Very Helpful!!!

  • Azi

    Hi mkyong,

    What if I like to split both space and comma at the same time.?

  • abdd

    Please fix the class name,

    from:
    StringTokennizer

    to:
    StringTokenizer

  • otto

    how to read column and match that column, so that can print a line

  • http://[email protected] fifa

    Hi, I’m getting this error when I run the Java code

    Exception in thread “AWT-EventQueue-0″ java.lang.NumberFormatException: For input string: “age”

    It is from this line
    Integer age = Integer.parseInt(stringTokenizer.nextElement().toString());

    Does anyone know what wrong with my code?

  • Hamdi

    Thnx alot …

  • J

    I can’t to get this work using a comma and a space
    im not seeing what you are doing

  • Sishir

    I am getting some exception in this programe…

    import java.util.StringTokenizer;

    public class App {
    public static void main(String[] args) {

    String str = “C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\school3″;

    StringTokenizer st2 = new StringTokenizer(str, “\”);

    while (st2.hasMoreElements()) {
    System.out.println(st2.nextElement());
    }
    }
    }

    • Mohit Tomar

      Try This.. Its working..

      import java.util.StringTokenizer;

      public class App {
      public static void main(String[] args) {

      String str = “C:’\’Program Files’\’Apache Software Foundation’\’Tomcat 6.0’\’webapps’\’school3″;

      StringTokenizer st2 = new StringTokenizer(str,”‘\'”);

      while (st2.hasMoreElements()) {
      System.out.println(st2.nextElement());
      }
      }
      }

  • gangasani mahesh reddy

    I did this is in easiest mode for understanding everyone please try this who are going to learn java tokenizers try this……………

    import java.util.StringTokenizer;
    class StringTokenizer
    {
    public static void main(String args[])
    {
    String pdetails=(“auu=isoluecine;ccu=proline;guu=valine;uuu=phenylalanine”);

    StringTokenizer st=new StringTokenizer(pdetails,”;”);

    System.out.println(“num of tokens ” +st.countTokens());

    while(st.hasMoreTokens())
    {
    System.out.println(st.nextToken());
    }
    }
    }

  • http://onlineseeker1000.wordpress.com onlineseeker

    you’v done an awesome task fella….. thanks…… cheers ! ! !

  • m24

    i m getting a nullPointerException can u plz help
    “Exception in thread “main” java.lang.NullPointerException
    at java.util.StringTokenizer.(StringTokenizer.java:199)
    at java.util.StringTokenizer.(StringTokenizer.java:221)
    at token.main(token.java:19)”
    my program is:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.StringTokenizer;

    public class token {

    public static void main(String[] args)
    {
    BufferedReader br=null;
    try
    {
    String line;
    br= new BufferedReader(new FileReader(“file.txt”));
    while((line=br.readLine())!=null)
    {
    System.out.println(line);
    }
    StringTokenizer st=new StringTokenizer(line,””);
    while(st.hasMoreTokens())
    {
    System.out.println(st.nextToken(line));
    }
    }
    catch (IOException e) {

    e.printStackTrace();
    }
    finally{
    try
    {
    if(br!=null)
    {
    br.close();
    }
    }
    catch(IOException e)
    {
    e.printStackTrace();
    }
    }

    }
    }

    • Mohit Tomar

      Check this out..

      import java.io.*;
      import java.util.StringTokenizer;

      public class App {

      public static void main(String[] args)
      {
      BufferedReader br=null;
      try
      {
      String line;
      br= new BufferedReader(new FileReader(“/home/mohit/Documents/Java/file.txt”));
      while((line=br.readLine())!=null)
      {
      StringTokenizer st=new StringTokenizer(line);
      while(st.hasMoreTokens())
      {
      System.out.println(st.nextToken());
      }
      }
      }
      catch (IOException e) {

      e.printStackTrace();
      }
      finally{
      try
      {
      if(br!=null)
      {
      br.close();
      }
      }
      catch(IOException e)
      {
      e.printStackTrace();
      }
      }
      }
      }

      • Mohit Tomar

        U have to pass the location of the file where ‘file.txt’ is located..

  • ahmadi

    please help me i want to red a text file chrarcter by chararcter and compare each chararcter if is equal print it.

  • http://[email protected] Bhavesh tamrakar

    Thanks,
    i have read of StringTonkenizer content but some how in ur site it is not completed, it is half on right side of page .
    Please make it complete visible sothat people benifited a lot.
    Thanks

    • http://www.mkyong.com mkyong

      Sorry, what you means by “half on right side”? I’m able to view the full page.

      Try refresh or clear your cache.

  • Pingback: String Tokenizer vs Scanner vs Split « tediscript.wordpress.com()

  • Anonymous

    Awesome guide. Thanks.

  • Amar

    taking string as abc-123 and display cba-321 in java string class

    • swarnim prabhat

      split the string with “-” as token and then reverse it and again append the both reverses string using StringBuilder class.

  • http://www.split-dalmatien.de to split

    thank you very much, for your great function!
    I’m new in the world of java, but it is like php

  • SureshMhz

    It’s useful, but it is suggested to better use split method, reference http://download.oracle.com/javase/1.5.0/docs/api/java/util/StringTokenizer.html

  • selvam

    It is very useful for me.
    Thank u for giving this information.

  • r30

    Your blog is very useful for me. Thanks!

    • http://www.ms2source.com Eulieboy

      thanks for ur site mr.mkyong! it’s useful to me..

      • Ilim ki dunia

        waqai mein bohat alla hai :) Stay blessed or sada suhagan raho :*