cstutoringcenter.com logo





E-mail:    Password:    

Become a premier member today to gain access to exclusive member benefits! Just $10.00 to join FOR LIFE!




NY Web Consulting


<< Tutorial 4
Tutorial 6 >>
Java tutorial index

Java StringTokenizer

Tutorial 5


Register or log in today to rate this tutorial!
Current ranking: / 5 stars with 25 votes.


Topics
What is a StringTokenizer?
Import Statements
Methods
Character Wrapper Class
Examples
Example 1
Example 2
Example 3
Example 4
Comments
Comments

What is a StringTokenizer?

In java, there is a way to break up a line of text into what are called tokens. A token is a smaller piece of a string. This method of breaking up tokens are come from the StringTokenizer class.

Let's say that we wanted to break up the following line of text into smaller pieces:

"Hello and welcome to programming"

Here, the token we need is just a simple white space. So here is how to declare a StringTokeizer object:

StringTokenizer name = new StringTokenizer(variable, Token(s));

where in the above, name is an appropriate name for the tokenizer object; variable is the name of a String variable you are using or even just a simple string; and token(s) is the token you are specifying.

In the above definition, if the second argument of the constructor is not specified, the token, by default, is a white space. If the token that is declared does not exist in the String you are searching through, the entire string is returned to you.

Import statements

In order for the StringTokenizer class to be used, you must import it from a certain library; here the util library.

An import statement always appears outside the class header line. So here is how the StringTokenizer statement will look:

import java.util.*;

public class XXXXXXXXXX {
  //code here
}

The above is specifically for the StringTokenizer class. There are many other libraries that can be used in java. When the time is needed to describe these, we will.

Methods

Here are the most used functions in the StringTokenizer class.

boolean hasMoreTokens()

This method will return a boolean value that will represent if there are any more tokens left in the line you are trying to tokenize. The true return will show that there is at least 1 more token in the line.

int countTokens()

This method will simply return an integer representing the number of tokens in the String. This method does not advance the position in the String.

String nextToken()

This method is the primary method of the class as it will get you the next piece of data in the String. The position in the string is changed after this method is called.

Below is an example showing these above methods.

Example 1:
StringTokenizer example

Download source code here (Right click - Save Target As...)

import java.util.StringTokenizer;
public class StringTokenizerExample{

  public static void main(String args[]){

        String s = "What on earth is going on here?";

        //by default, a white space:
	StringTokenizer st = new StringTokenizer(s);

        //when there are still more tokens, print out the
        //next one:
	while(st.hasMoreTokens())
		System.out.println(st.nextToken());
  } //main
} //class

This program will simply break up the String named s into 7 pieces, each on a new line based on the println statement.

Example 2:
StringTokenizer example with arrays

Download source code here (Right click - Save Target As...)

This program will take a String with multiple tokens and place each part in an array of Strings. It will then find the index of the largest String in the array.

import java.util.StringTokenizer;
public class StringTokenizerExample2{
  public static void main(String args[]){

          String s = "Five+Three=Nine-One";
	  String arr[];

          //declare it with 3 tokens as seen above:
	  StringTokenizer st = new StringTokenizer(s, "+=-");

	  //the array size is the number of tokens in the String:
	  arr = new String[st.countTokens()];

          //when there are still more tokens, place it in the array:
	  int i = 0;
          while(st.hasMoreTokens()){
		arr[i] = st.nextToken();
                i++;
          }

	  //determine the word with the largest length:
          int indexMax = 0;
          for(int i = 1; i < arr.length; i++){
             if(arr[i].length() > arr[indexMax].length())
			indexMax = i;
          }

	  System.out.println("The largest element is in index: " 
                + indexMax);

  } //main
} //class

The program first starts by declaring the StringTokenizer with 3 tokens, the plus sign, equals sign and minus sign. These are determined by looking at the String in the program.

The array we need is now determined to be the number of tokens in the String. Here, the countTokens() method will return 4 so in turn, the array will be of size 4.

The program then places each element in the String into the array making use of the nextToken() method in the while loop. Once complete, we need to then determine the index of the biggest word. This is simply done by comparing each element of the array with the current maximum element.

The output from the above program is:

The largest element is in index: 1

Example 3:
StringTokenizer example

Download source code here (Right click - Save Target As...)

import java.util.StringTokenizer;
public class StringTokenizerExample3{

  public static void main(String args[]){

        String s = "1,2,4,8,16,7,11,13,10";
        int sum = 0;

        //use the comma as the token:
	StringTokenizer st = new StringTokenizer(s, ",");

        //when there are still more tokens, print out the
        //next one:
	while(st.hasMoreTokens())
		sum += Integer.parseInt(st.nextToken());

        System.out.println("The sum is: " + sum);

  } //main
} //class

This program will simply break up the String named s by using the comma as the token. It then calculates the sum of the numbers in the String and prints the result. The output of the program is:

The sum is: 72

Character Wrapper Classes

Much like the wrapper classes for numeric values that we have already seen (Integer, Double, Float etc), an important class that contains some useful methods is the character wrapper class. There are methods that will check if a character is a digit, letter etc. as well as uppercase, lowercase etc. An example showing some of these methods is below:

Example 4:
Character Wrapper Class

Download source code here (Right click - Save Target As...)

public class CharacterWrapperExample{
  public static void main(String args[]){
    if(args.length == 0){
       System.out.println("A String argument is needed.");
       System.exit(1);
    }

    String s = args[0];
    int upper = 0, lower = 0, letter = 0, digit = 0, space = 0;

    for(int i = 0; i < s.length(); i++){
      if(Character.isUpperCase(s.charAt(i))) upper++;
      if(Character.isLowerCase(s.charAt(i))) lower++;
      if(Character.isDigit(s.charAt(i))) digit++;
      if(Character.isLetter(s.charAt(i))) letter++;
      if(Character.isWhitespace(s.charAt(i))) space++;
    }

    System.out.println("There are:\n" +
      upper + " uppercase characters\n" +
      lower + " lowercase characters\n" +
      digit + " digit characters\n" +
      letter + " letters\n" +
      space + " white spaces.");
  }//main
} //class

The output from running the above program is:

There are:
2 uppercase characters
13 lowercase characters
0 digit characters
15 letters
3 white spaces.

Here is an explanation of the above methods:

boolean isDigit(char c)

This method will return true if the character argument is a digit from 0 to 9. Else, it will return false.

boolean isLetter(char c)

This method will return true if the character argument is a letter from, EITHER UPPERCASE OR LOWERCASE. Else, it will return false.

boolean isUpperCase(char c)

This method will return true if the character argument is an uppercase letter. Else, it will return false.

boolean isLowerCase(char c)

This method will return true if the character argument is a lowercase letter. Else, it will return false.

boolean isWhiteSpace(char c)

This method will return true if the character argument is a white space character. Else, it will return false.

As seen in the program, these methods are utilized to keep track of the different types of characters in the String argument.


<< Tutorial 4
Tutorial 6 >>
Java tutorial index


Comments

Please feel free to leave a comment! Just keep it peaceful is all we ask and try to be as informative as possible to help others. Spam will NOT be tolerated!

Reviewing C++

Reviewing C++

Print: $39.99

Reviewing Java

Reviewing Java

Print: $34.99