1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class.

Slides:



Advertisements
Similar presentations
1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
Advertisements

Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
More Java Syntax. Scanner class Revisited The Scanner class is a class in java.util, which allows the user to read values of various types. There are.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Chapter 7: The String class We’ll go through some of this quickly!
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Exception examples. import java.io.*; import java.util.*; class IO { private String line; private StringTokenizer tokenizer; public void newline(DataInputStream.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
1 String Buffer & String Tokenizer Overview l Overview of String Buffer class and Methods l Overview of String Tokenizer class and methods l Preview: Notions.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
String Tokenization What is String Tokenization?
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
StringBuffer class  Alternative to String class  Can be used wherever a string is used  More flexible than String  Has three constructors and more.
Fundamental Programming Structures in Java: Strings.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
1 Repetition structures [cont’d] Overview l Nested Loops l Sentinel-Controlled loop l Avoiding Number Format exception.
1 One-Dimensional Arrays  What are and Why 1-D arrays?  1-D Array Declaration  Accessing elements of a 1-D Array  Initializer List  Passing Array.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Computer Programming 2 Lecture 5: String Processing Part b: Class StringTokenizer Prepared & Presented by: Mahmoud Rafeek Alfarra MINISTRY OF EDUCATION.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Objectives ► Become familiar with the class String ► ► Learn how to use input and output dialog boxes in a program ► ► Learn how to tokenize the input.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 String Comparisons Compare string contents with the equals(String s) method not == String s0 = “ Java”;
Java 1.5 The New Java Mike Orsega Central Carolina CC.
String Handling StringBuffer class character class StringTokenizer class.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Geoff Holmes Date Math Weighted Distr Strings String methods Tokenizers System Examples Utility Classes (Chapter 17) import java.util.*;
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
1 CHAPTER 3 StringTokenizer. 2 StringTokenizer CLASS There are BufferedReader methods to read a line (i.e. a record) and a character, but not just a single.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Chapter 5 Programming with Objects and Classes OO Programming Concepts OO Programming Concepts Declaring and Creating Objects Declaring and Creating Objects.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Chapter 9 1 Chapter 9 – Part 2 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
Programming Fundamentals 2: Libraries/ F II Objectives – –utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Strings.
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Lecture 07 String Jaeki Song.
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
F II 6. Using Libraries Objectives
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class l Some StringBuffer methods l Creating a String object from a StringBuffer object l Preview: 2D-arrays

2 StringTokenizer class l 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” l 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. l The StringTokenizer constructors are: StringTokenizer(String str)Uses white space characters as a delimiters. The delimiters are not returned. StringTokenizer(String str, String delimiters) delimiters is a string that specifies the delimiters. The delimiters are not returned. StringTokenizer(String str, String delimiters, boolean delimAsToken) If delimAsToken is true, then each delimiter is also returned as a token; otherwise delimiters are not returned.

3 Some StringTokenizer methods l Some StringTokenizer methods are: l 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... } 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 NoSuchElementException Returns the next token as a string. Throws an exception if there are no more tokens String nextToken(String newDelimiters) throws NoSuchElementException Returns the next token as a string and sets the delimiters to newDelimiters. Throws an exception if there are no more tokens.

4 StringTokenizer examples StringTokenizer tokenizer = new String(stringName); int tokenCount = tokenizer.countTokens( ); for(int k = 1; k <= tokenCount; k++) { String token = tokenizer.nextToken( ); // process token... } l 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( ) ); }

5 StringTokenizer examples (Cont’d) l 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"); }

6 StringTokenizer examples (Cont’d) catch(NumberFormatException e) { System.err.println("Error - an invalid float value read"); } l Example3: Given that a text file grades.txt contains ids and quiz grades of students: the program on the next slide will display the id, number of quizzes taken, and average of each student:

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 QuizzesAverage\n"); 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); }

8 StringBuffer class l A String object is not modifiable once created (i.e., it is immutable). l Modifiable (i.e., mutable) strings are supplied by the StringBuffer class of the package java.lang l A String buffer object can be created using any of the following constructors: l Note: If the capacity of a StringBuffer object is exceeded, the buffer is automatically expanded to accommodate the additional characters. StringBuffer( )Creates a StringBuffer object containing no characters in it with an initial capacity of 16 characters StringBuffer(int size) throws NegativeArraySizeException Creates a StringBuffer object containing no characters in it with an initial capacity of size characters. Throws an exception if size < 0 StringBuffer(String str)Creates a StringBuffer object containing str with an initial capacity of (str.length( ) + 16) characters

9 Some StringBuffer methods l The StringBuffer class has some methods that are similar to those in the String class (e.g., length( ), charAt(index), substring(index), substring(index1, index2) The following are some of the methods of the StringBuffer class: int length( )Returns the number of characters in the buffer int capacity( )Returns the capacity of the buffer char charAt(i)Returns the character at position i void setCharAt(i, ch)Replaces char at i with ch StringBuffer append(ob)Appends the string form of the object ob or a primitive value to the buffer. StringBuffer insert(i, ob)Inserts the string form of the object ob (or a primitive value) at i StringBuffer replace(s, f, str)Replaces the substring from s to f – 1 with str StringBuffer delete(s, f) StringBiffer deleteCharAt(i) Deletes characters from s to f - 1 Deletes the character at i StringBuffer reverse( )Reverses the contents of buffer. String toString( )Returns the contents of buffer as a string.

10 Creating a String object from a StringBuffer object Example: public class InsertTest { public static void main(String[ ] args) { StringBuffer sb = new StringBuffer("Drink Java!"); System.out.println(sb); sb.insert(6, “Hot "); System.out.println(sb); } l Creating a String object from a StringBuffer object A string object can be created from a StringBuffer object using one of the following StringBuffer methods: String toString( )Returns the string contained in the invoking StringBuffer object. String substring(int index)Returns the substring from index to the end of the invoking StringBuffer object. String substring(int index1, int index2)Returns the substring from index1 to index2 – 1 of the invoking StringBuffer object.

11 Creating a String object from a StringBuffer object (Cont’d) Example: public class ReverseString { public static void main(String[ ] args) { String str = "What's going on?"; System.out.println(reverseString(str)); } public static String reverseString(String source) { StringBuffer dest = new StringBuffer(source); dest.reverse( ); return dest.toString( ); }