SlideShare a Scribd company logo
1 of 7
StringTokenization
               Overview

StringTokenizer class

Some StringTokenizer methods

StringTokenizer examples




                               1
StringTokenizer class
A token is a portion of a string that is separated from another
portion of that string by one or more chosen characters (called
delimiters).


Example: Assuming that a while space character (i.e., blank, ‘n’
(new line ), ‘t’ (tab), or ‘r’ (carriage return)) is a delimiter, then the
string: “I like KFUPM very much” has the tokens: “I”, “like”,
“KFUPM”, “very”, and “much”

The StringTokenizer class contained in the java.util package can be
used to break a string into separate tokens. This is particularly useful
in those situations in which we want to read and process one token
at a time; the BufferedReader class does not have a method to read
one token at a time.

The StringTokenizer constructors are:
  StringTokenizer(String str)     Uses white space characters
                                  as a delimiters. The
                                  delimiters are not returned.

   StringTokenizer(String str,   delimiters is a string that
              String delimiters) specifies the delimiters. The
                                 delimiters are not returned.

   StringTokenizer(String str,        If delimAsToken is true, then
      String delimiters, boolean      each delimiter is also
                                      returned as a token; otherwise
                delimAsToken)
                                      delimiters are not returned.

                                                                      2
Some StringTokenizer methods
Some StringTokenizer methods are:

int countTokens( )                Using the current set of
                                  delimiters, the method returns
                                  the number of tokens left.
boolean hasMoreTokens( )          Returns true if one or more
                                  tokens remain in the string;
                                  otherwise it returns false.
String nextToken( ) throws        Returns the next token as a
  NoSuchElementException          string. Throws an exception if
                                  there are no more tokens
String nextToken(String           Returns the next token as a
    newDelimiters) throws         string and sets the delimiters to
                                  newDelimiters. Throws an
  NoSuchElementException
                                  exception if there are no more
                                  tokens.


To break a string into tokens, a loop having one of the following
forms may be used:

StringTokenizer tokenizer = new StringTokenizer(stringName);
while(tokenizer.hasMoreTokens( ))
{
     String token = tokenizer.nextToken( );
       // process the token
       . . .
}

                                                                 3
StringTokenizer examples
StringTokenizer tokenizer = new StringTokenizer (stringName);
int tokenCount = tokenizer.countTokens( );
for(int k = 1; k <= tokenCount; k++)
{
    String token = tokenizer.nextToken( );
    // process token
    . . .
}

Example1:

import java.util.StringTokenizer;

public class Tokenizer1
{
   public static void main(String[ ] args)
   {
      StringTokenizer wordFinder = new StringTokenizer
                                 ("We like KFUPM very much");
      while( wordFinder.hasMoreTokens( ) )
          System.out.println( wordFinder.nextToken( ) );
   }
}



                                                           4
StringTokenizer examples (Cont’d)
   Example2: The following program reads grades from the keyboard and
   finds their average. The grades are read in one line.

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

public class Tokenizer5
{
   public static void main(String[ ] args) throws IOException
   {
           BufferedReader stdin = new BufferedReader(new
                                         InputStreamReader(System.in));
           System.out.println("Enter grades in one line:");
           String inputLine = stdin.readLine( );
           StringTokenizer tokenizer = new StringTokenizer(inputLine);
           int count = 0;
           float grade, sum = 0.0F;
           try {
              while( tokenizer.hasMoreTokens( ) ) {
                   grade = Float.parseFloat( tokenizer.nextToken( ) );
                   if(grade >= 0 && grade <= 100)
                   {
                        sum += grade;
                        count++;
                    }
                }
                if(count > 0)
                   System.out.println("nThe average = "+ sum / count);
                else
                   System.out.println("No valid grades entered");
   }
                                                                     5
StringTokenizer examples (Cont’d)
          catch(NumberFormatException e)
          {
             System.err.println("Error - an invalid float value read");
          }
    }
}

    Example3: Given that a text file grades.txt contains ids and quiz grades
    of students:

    980000           50.0       30.0      40.0
    975348           50.0       35.0
    960035           80.0       70.0      60.0       75.0
    950000           20.0       40.0
    996245           65.0       70.0      80.0       60.0       45.0
    987645           50.0       60.0

    the program on the next slide will display the id, number of quizzes
    taken, and average of each student:




                                                                       6
StringTokenizer examples (Cont’d)
import java.io.*;
import java.util.StringTokenizer;

public class Tokenizer6
{
   public static void main(String[ ] args) throws IOException
   {
        BufferedReader inputStream = new BufferedReader(new

                    FileReader("grades.txt"));
        StringTokenizer tokenizer;
        String inputLine, id;
        int count;
        float sum;
        System.out.println("ID#    Number of Quizzes          Averagen");

        while((inputLine = inputStream.readLine( )) != null)
        {
          tokenizer = new StringTokenizer(inputLine);
          id = tokenizer.nextToken( );
          count = tokenizer.countTokens( );
          sum = 0.0F;
          while( tokenizer.hasMoreTokens( ) )
             sum += Float.parseFloat( tokenizer.nextToken( ) );

            System.out.println(id + "    " + count + "            ”
                 + sum / count);
        }
    }
}

                                                                      7

More Related Content

What's hot

Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerAiman Hud
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NETJaya Kumari
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner classsimarsimmygrewal
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Featuresindia_mani
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMmanish kumar
 

What's hot (19)

Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
 
Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
M C6java3
M C6java3M C6java3
M C6java3
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
package
packagepackage
package
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
What Do You Mean By NUnit
What Do You Mean By NUnitWhat Do You Mean By NUnit
What Do You Mean By NUnit
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 
Lesson2
Lesson2Lesson2
Lesson2
 

Viewers also liked

Pattern recognition in medical images
Pattern recognition in medical imagesPattern recognition in medical images
Pattern recognition in medical imagesJayabalanRajalakshmi
 
Software Agent Oriented Programming
Software Agent Oriented Programming Software Agent Oriented Programming
Software Agent Oriented Programming JayabalanRajalakshmi
 
Advanced data structures and algorithms
Advanced data structures and algorithmsAdvanced data structures and algorithms
Advanced data structures and algorithmsJayabalanRajalakshmi
 
Requirements validation techniques (rv ts) practiced in industry studies of...
Requirements validation techniques (rv ts) practiced in industry   studies of...Requirements validation techniques (rv ts) practiced in industry   studies of...
Requirements validation techniques (rv ts) practiced in industry studies of...JayabalanRajalakshmi
 

Viewers also liked (6)

Pattern recognition in medical images
Pattern recognition in medical imagesPattern recognition in medical images
Pattern recognition in medical images
 
Arte precolombino
Arte precolombinoArte precolombino
Arte precolombino
 
Que es el_amor
Que es el_amorQue es el_amor
Que es el_amor
 
Software Agent Oriented Programming
Software Agent Oriented Programming Software Agent Oriented Programming
Software Agent Oriented Programming
 
Advanced data structures and algorithms
Advanced data structures and algorithmsAdvanced data structures and algorithms
Advanced data structures and algorithms
 
Requirements validation techniques (rv ts) practiced in industry studies of...
Requirements validation techniques (rv ts) practiced in industry   studies of...Requirements validation techniques (rv ts) practiced in industry   studies of...
Requirements validation techniques (rv ts) practiced in industry studies of...
 

Similar to string tokenization

ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner classdeepsxn
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDrRajeshreeKhande
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfadinathassociates
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfabdulkadar1977
 
Java Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfJava Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfadinathassociates
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 

Similar to string tokenization (20)

ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner class
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdf
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdf
 
Java Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfJava Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdf
 
130706266060138191
130706266060138191130706266060138191
130706266060138191
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Day2
Day2Day2
Day2
 
core java
 core java core java
core java
 
Strings
StringsStrings
Strings
 
The Art of Clean Code
The Art of Clean CodeThe Art of Clean Code
The Art of Clean Code
 
Utility.ppt
Utility.pptUtility.ppt
Utility.ppt
 

Recently uploaded

General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Recently uploaded (20)

General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

string tokenization

  • 1. StringTokenization Overview StringTokenizer class Some StringTokenizer methods StringTokenizer examples 1
  • 2. StringTokenizer class A token is a portion of a string that is separated from another portion of that string by one or more chosen characters (called delimiters). Example: Assuming that a while space character (i.e., blank, ‘n’ (new line ), ‘t’ (tab), or ‘r’ (carriage return)) is a delimiter, then the string: “I like KFUPM very much” has the tokens: “I”, “like”, “KFUPM”, “very”, and “much” The StringTokenizer class contained in the java.util package can be used to break a string into separate tokens. This is particularly useful in those situations in which we want to read and process one token at a time; the BufferedReader class does not have a method to read one token at a time. The StringTokenizer constructors are: StringTokenizer(String str) Uses white space characters as a delimiters. The delimiters are not returned. StringTokenizer(String str, delimiters is a string that String delimiters) specifies the delimiters. The delimiters are not returned. StringTokenizer(String str, If delimAsToken is true, then String delimiters, boolean each delimiter is also returned as a token; otherwise delimAsToken) delimiters are not returned. 2
  • 3. Some StringTokenizer methods Some StringTokenizer methods are: int countTokens( ) Using the current set of delimiters, the method returns the number of tokens left. boolean hasMoreTokens( ) Returns true if one or more tokens remain in the string; otherwise it returns false. String nextToken( ) throws Returns the next token as a NoSuchElementException string. Throws an exception if there are no more tokens String nextToken(String Returns the next token as a newDelimiters) throws string and sets the delimiters to newDelimiters. Throws an NoSuchElementException exception if there are no more tokens. To break a string into tokens, a loop having one of the following forms may be used: StringTokenizer tokenizer = new StringTokenizer(stringName); while(tokenizer.hasMoreTokens( )) { String token = tokenizer.nextToken( ); // process the token . . . } 3
  • 4. StringTokenizer examples StringTokenizer tokenizer = new StringTokenizer (stringName); int tokenCount = tokenizer.countTokens( ); for(int k = 1; k <= tokenCount; k++) { String token = tokenizer.nextToken( ); // process token . . . } Example1: import java.util.StringTokenizer; public class Tokenizer1 { public static void main(String[ ] args) { StringTokenizer wordFinder = new StringTokenizer ("We like KFUPM very much"); while( wordFinder.hasMoreTokens( ) ) System.out.println( wordFinder.nextToken( ) ); } } 4
  • 5. StringTokenizer examples (Cont’d) Example2: The following program reads grades from the keyboard and finds their average. The grades are read in one line. import java.io.*; import java.util.StringTokenizer; public class Tokenizer5 { public static void main(String[ ] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter grades in one line:"); String inputLine = stdin.readLine( ); StringTokenizer tokenizer = new StringTokenizer(inputLine); int count = 0; float grade, sum = 0.0F; try { while( tokenizer.hasMoreTokens( ) ) { grade = Float.parseFloat( tokenizer.nextToken( ) ); if(grade >= 0 && grade <= 100) { sum += grade; count++; } } if(count > 0) System.out.println("nThe average = "+ sum / count); else System.out.println("No valid grades entered"); } 5
  • 6. StringTokenizer examples (Cont’d) catch(NumberFormatException e) { System.err.println("Error - an invalid float value read"); } } } Example3: Given that a text file grades.txt contains ids and quiz grades of students: 980000 50.0 30.0 40.0 975348 50.0 35.0 960035 80.0 70.0 60.0 75.0 950000 20.0 40.0 996245 65.0 70.0 80.0 60.0 45.0 987645 50.0 60.0 the program on the next slide will display the id, number of quizzes taken, and average of each student: 6
  • 7. StringTokenizer examples (Cont’d) import java.io.*; import java.util.StringTokenizer; public class Tokenizer6 { public static void main(String[ ] args) throws IOException { BufferedReader inputStream = new BufferedReader(new FileReader("grades.txt")); StringTokenizer tokenizer; String inputLine, id; int count; float sum; System.out.println("ID# Number of Quizzes Averagen"); while((inputLine = inputStream.readLine( )) != null) { tokenizer = new StringTokenizer(inputLine); id = tokenizer.nextToken( ); count = tokenizer.countTokens( ); sum = 0.0F; while( tokenizer.hasMoreTokens( ) ) sum += Float.parseFloat( tokenizer.nextToken( ) ); System.out.println(id + " " + count + " ” + sum / count); } } } 7