Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using StringTokenizer Class

StringTokenizer  is shipped in java.util package. This can be used to split a string using a given delimiter. Space character is the default delimiter for any string.
There are three important methods in StringTokenizer class.
  • countTokens()  : returns the number of tokens.
  • hasMoreTokens() : returns true if more tokens are available .
  • nextToken() :returns the current token.
lets see some java code to understand these methods.


//© http://imagocomputing.blogspot.com/
import java.util.StringTokenizer;
class TokenizerDemo {
public static void main(String args[]){
String MyStr="Sajith#Nimal#Kamal#Sunil";
StringTokenizer tokens=new StringTokenizer(MyStr,"#");
System.out.println("Real String : " + MyStr);
System.out.println("Number of tokens: " + tokens.countTokens());
int i=1;
while(tokens.hasMoreTokens()){
System.out.println("Token " + i +" \t: " + tokens.nextToken());
i++;
}
}
}
output :


A Practical Example:
//© http://imagocomputing.blogspot.com/
import java.util.StringTokenizer;

class GetExtensionDemo {
static String getFileExtension(String filePath){
StringTokenizer stk=new StringTokenizer(filePath,".");
String FileExt="";
while(stk.hasMoreTokens()){
FileExt=stk.nextToken();
}
return FileExt;
}

public static void main(String[] args){
String path1="/usr/bin/myProg.pl";
System.out.println("File path : " + path1 + " File extension : " + getFileExtension(path1));
String path2="C:\\about.bmp";
System.out.println("File path : " + path2 + " File extension : " + getFileExtension(path2));
}
}
Output :
Since : JDK1.0
 


This post first appeared on Let's Learn Java API, please read the originial post: here

Share the post

Using StringTokenizer Class

×

Subscribe to Let's Learn Java Api

Get updates delivered right to your inbox!

Thank you for your subscription

×