SlideShare a Scribd company logo
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 Komputer
Aiman Hud
 
Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
Aravindreddy Mokireddy
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
M C6java3
M C6java3M C6java3
M C6java3
mbruggen
 
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
Suresh Mohta
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
Jayant Parida
 
package
packagepackage
package
sweetysweety8
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
Jaya Kumari
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
What Do You Mean By NUnit
What Do You Mean By NUnitWhat Do You Mean By NUnit
What Do You Mean By NUnit
Anand Kumar Rajana
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
simarsimmygrewal
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
SURBHI SAROHA
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
javeed_mhd
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
india_mani
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
SURBHI SAROHA
 
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
manish kumar
 
Lesson2
Lesson2Lesson2
Lesson2
Arpan91
 

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 images
JayabalanRajalakshmi
 
Arte precolombino
Arte precolombinoArte precolombino
Arte precolombino
Emilio Morales
 
Que es el_amor
Que es el_amorQue es el_amor
Que es el_amor
yasmanyromero
 
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 algorithms
JayabalanRajalakshmi
 
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 class
deepsxn
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
DrRajeshreeKhande
 
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
adinathassociates
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
Snehal Harawande
 
Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
ShehabEldinSaid
 
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
abdulkadar1977
 
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
adinathassociates
 
130706266060138191
130706266060138191130706266060138191
130706266060138191
Tanzeel Ahmad
 
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
Abdul Samee
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
SantoshSurwade2
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 
Day2
Day2Day2
core java
 core java core java
core java
dssreenath
 
Strings
StringsStrings
Strings
Imad Ali
 
The Art of Clean Code
The Art of Clean CodeThe Art of Clean Code
The Art of Clean Code
Yael Zaritsky Perez
 
Utility.ppt
Utility.pptUtility.ppt
Utility.ppt
BruceLee275640
 

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

ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 

Recently uploaded (20)

ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 

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