Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class."— Presentation transcript:

1 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 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 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 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 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 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: 98000050.030.040.0 97534850.035.0 96003580.070.060.075.0 95000020.040.0 99624565.070.080.060.045.0 98764550.060.0 the program on the next slide will display the id, number of quizzes taken, and average of each student:

7 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 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 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 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 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( ); }


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

Similar presentations


Ads by Google