String Tokenizer and String Buffer classes Overview l
String. Tokenizer and String. Buffer classes Overview l String. Tokenizer class l Some String. Tokenizer methods l String. Tokenizer examples l String. Buffer class l Some String. Buffer methods l Creating a String object from a String. Buffer object l Preview: 2 D-arrays 1
String. Tokenizer 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 String. Tokenizer 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 Buffered. Reader class does not have a method to read one token at a time. l The String. Tokenizer constructors are: String. Tokenizer(String str) Uses white space characters as a delimiters. The delimiters are not returned. String. Tokenizer(String str, String delimiters) delimiters is a string that specifies the delimiters. The delimiters are not returned. String. Tokenizer(String str, If delim. As. Token is true, then String delimiters, boolean each delimiter is also returned as a token; otherwise delim. As. Token) delimiters are not returned. 2
Some String. Tokenizer methods l l Some String. Tokenizer methods are: int count. Tokens( ) Using the current set of delimiters, the method returns the number of tokens left. boolean has. More. Tokens( ) Returns true if one or more tokens remain in the string; otherwise it returns false. String next. Token( ) throws No. Such. Element. Exception Returns the next token as a string. Throws an exception if there are no more tokens String next. Token(String new. Delimiters) throws No. Such. Element. Exception Returns the next token as a string and sets the delimiters to new. Delimiters. Throws an exception if there are no more tokens. To break a string into tokens, a loop having one of the following forms may be used: String. Tokenizer tokenizer = new String. Tokenizer(string. Name); while(tokenizer. has. More. Tokens( )) { String token = tokenizer. next. Token( ); // process the token. . . } 3
String. Tokenizer examples String. Tokenizer tokenizer = new String(string. Name); int token. Count = tokenizer. count. Tokens( ); for(int k = 1; k <= token. Count; k++) { String token = tokenizer. next. Token( ); // process token . . . } l Example 1: import java. util. String. Tokenizer; public class Tokenizer 1 { public static void main(String[ ] args) { String. Tokenizer word. Finder = new String. Tokenizer ("We like KFUPM very much"); while( word. Finder. has. More. Tokens( ) ) System. out. println( word. Finder. next. Token( ) ); } } 4
String. Tokenizer examples (Cont’d) l Example 2: 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. String. Tokenizer; public class Tokenizer 5 { public static void main(String[ ] args) throws IOException { Buffered. Reader stdin = new Buffered. Reader(new Input. Stream. Reader(System. in)); System. out. println("Enter grades in one line: "); String input. Line = stdin. read. Line( ); String. Tokenizer tokenizer = new String. Tokenizer(input. Line); int count = 0; float grade, sum = 0. 0 F; try { while( tokenizer. has. More. Tokens( ) ) { grade = Float. parse. Float( tokenizer. next. Token( ) ); if(grade >= 0 && grade <= 100) { sum += grade; count++; } } if(count > 0) System. out. println("n. The average = "+ sum / count); else System. out. println("No valid grades entered"); } 5
String. Tokenizer examples (Cont’d) catch(Number. Format. Exception e) { System. err. println("Error - an invalid float value read"); } } } l Example 3: Given that a text file grades. txt contains ids and quiz grades of students: 980000 975348 960035 950000 996245 987645 50. 0 80. 0 20. 0 65. 0 50. 0 35. 0 70. 0 40. 0 70. 0 60. 0 40. 0 60. 0 75. 0 80. 0 60. 0 45. 0 the program on the next slide will display the id, number of quizzes taken, and average of each student: 6
String. Tokenizer examples (Cont’d) import java. io. *; import java. util. String. Tokenizer; public class Tokenizer 6 { public static void main(String[ ] args) throws IOException { Buffered. Reader input. Stream = new Buffered. Reader(new File. Reader("grades. txt")); String. Tokenizer tokenizer; String input. Line, id; int count; float sum; System. out. println("ID# Number of Quizzes Averagen"); while((input. Line = input. Stream. read. Line( )) != null) { tokenizer = new String. Tokenizer(input. Line); id = tokenizer. next. Token( ); count = tokenizer. count. Tokens( ); sum = 0. 0 F; while( tokenizer. has. More. Tokens( ) ) sum += Float. parse. Float( tokenizer. next. Token( ) ); System. out. println(id + " + sum / count); " + count + " ” } } } 7
String. Buffer 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 String. Buffer class of the package java. lang l A String buffer object can be created using any of the following constructors: l String. Buffer( ) Creates a String. Buffer object containing no characters in it with an initial capacity of 16 characters String. Buffer(int size) throws Negative. Array. Size. Exception Creates a String. Buffer object containing no characters in it with an initial capacity of size characters. Throws an exception if size < 0 String. Buffer(String str) Creates a String. Buffer object containing str with an initial capacity of (str. length( ) + 16) characters Note: If the capacity of a String. Buffer object is exceeded, the buffer is automatically expanded to accommodate the additional characters. 8
Some String. Buffer methods l The String. Buffer class has some methods that are similar to those in the String class (e. g. , length( ), char. At(index), substring(index), substring(index 1, index 2) l The following are some of the methods of the String. Buffer class: int length( ) Returns the number of characters in the buffer int capacity( ) Returns the capacity of the buffer char. At(i) Returns the character at position i void set. Char. At(i, ch) Replaces char at i with ch String. Buffer append(ob) Appends the string form of the object ob or a primitive value to the buffer. String. Buffer insert(i, ob) Inserts the string form of the object ob (or a primitive value) at i String. Buffer replace(s, f, str) Replaces the substring from s to f – 1 with str String. Buffer delete(s, f) String. Biffer delete. Char. At(i) Deletes characters from s to f - 1 Deletes the character at i String. Buffer reverse( ) Reverses the contents of buffer. String to. String( ) Returns the contents of buffer as a string. 9
Creating a String object from a String. Buffer object Example: public class Insert. Test { public static void main(String[ ] args) { String. Buffer sb = new String. Buffer("Drink Java!"); System. out. println(sb); sb. insert(6, “Hot "); System. out. println(sb); } } l Creating a String object from a String. Buffer object A string object can be created from a String. Buffer object using one of the following String. Buffer methods: String to. String( ) Returns the string contained in the invoking String. Buffer object. String substring(int index) Returns the substring from index to the end of the invoking String. Buffer object. String substring(int index 1, int index 2) Returns the substring from index 1 to index 2 – 1 of the invoking String. Buffer object. 10
Creating a String object from a String. Buffer object (Cont’d) Example: public class Reverse. String { public static void main(String[ ] args) { String str = "What's going on? "; System. out. println(reverse. String(str)); } public static String reverse. String(String source) { String. Buffer dest = new String. Buffer(source); dest. reverse( ); return dest. to. String( ); } } 11
- Slides: 11