Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live.

Similar presentations


Presentation on theme: "Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live."— Presentation transcript:

1 Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live by what they hear…

2 Liang,Introduction to Java Programming,revised by Dai-kaiyu 2 Objectives To use the String class to process fixed strings (§7.2). To use the Character class to process a single character (§7.3). To use the StringBuffer class to process flexible strings (§7.4). To use the StringTokenizer class to extract tokens from a string (§7.5). To know the differences among the String, StringBuffer, and StringTokenizer classes (§7.2-7.5). To use the JDK 1.5 Scanner class for console input and scan tokens using words as delimiters (§7.6). To input primitive values and strings from the keyboard using the Scanner class (§7.7). To learn how to pass strings to the main method from the command line (§7.8).

3 Liang,Introduction to Java Programming,revised by Dai-kaiyu 3 Introduction String and character processing  Class java.lang.String  Class java.lang.StringBuffer  Class java.lang.Character  Class java.util.StringTokenizer

4 Liang,Introduction to Java Programming,revised by Dai-kaiyu 4 Fundamentals of Characters and Strings Characters  “Building blocks” of Java source programs String  Series of characters treated as single unit  May include letters, digits, etc.  Object of class String

5 Liang,Introduction to Java Programming,revised by Dai-kaiyu 5 The String Class Constructing a String:  String message = "Welcome to Java“;  String message = new String("Welcome to Java“);  String s = new String(); Obtaining String length and Retrieving Individual Characters in a string String String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings

6 Liang,Introduction to Java Programming,revised by Dai-kaiyu 6

7 7 Constructing Strings String newString = new String(stringLiteral); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java";

8 Liang,Introduction to Java Programming,revised by Dai-kaiyu 8 1 // StringConstructors.java 2 // This program demonstrates the String class constructors. 3 4 // Java extension packages 5 import javax.swing.*; 6 7 public class StringConstructors { 8 9 // test String constructors 10 public static void main( String args[] ) 11 { 12 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 13 'd', 'a', 'y' }; 14 byte byteArray[] = { ( byte ) 'n', ( byte ) 'e', 15 ( byte ) 'w', ( byte ) ' ', ( byte ) 'y', 16 ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' }; 17 18 StringBuffer buffer; 19 String s, s1, s2, s3, s4, s5, s6, s7, output; 20 21 s = new String( "hello" ); 22 buffer = new StringBuffer( "Welcome to Java Programming!" ); 23 24 // use String constructors 25 s1 = new String(); 26 s2 = new String( s ); 27 s3 = new String( charArray ); 28 s4 = new String( charArray, 6, 3 ); 29 s5 = new String( byteArray, 4, 4 ); 30 s6 = new String( byteArray ); 31 s7 = new String( buffer ); 32 Constructor copies StringBuffer Constructor copies byte-array subsetConstructor copies byte arrayConstructor copies character- array subset Constructor copies character array Constructor copies String String default constructor instantiates empty string

9 Liang,Introduction to Java Programming,revised by Dai-kaiyu 9 33 // append Strings to output 34 output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 + 35 "\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6 + 36 "\ns7 = " + s7; 37 38 JOptionPane.showMessageDialog( null, output, 39 "Demonstrating String Class Constructors", 40 JOptionPane.INFORMATION_MESSAGE ); 41 42 System.exit( 0 ); 43 } 44 45 } // end class StringConstructors

10 Liang,Introduction to Java Programming,revised by Dai-kaiyu 10 Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML";

11 Liang,Introduction to Java Programming,revised by Dai-kaiyu 11 Trace Code String s = "Java"; s = "HTML";

12 Liang,Introduction to Java Programming,revised by Dai-kaiyu 12 Trace Code String s = "Java"; s = "HTML";

13 Liang,Introduction to Java Programming,revised by Dai-kaiyu 13 Canonical Strings Since strings are immutable, to improve efficiency and save memory, the JVM stores two String objects in the same object if they were created with the same string literal using the shorthand initializer. Such a string is referred to as a canonical string. You can also use a String object’s intern method to return a canonical string, which is the same string that is created using the shorthand initializer.

14 Liang,Introduction to Java Programming,revised by Dai-kaiyu 14 Examples display s1 == s is false s2 == s is true s == s3 is true

15 Liang,Introduction to Java Programming,revised by Dai-kaiyu 15 Examples display s1 == s is false s2 == s is true s == s3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.

16 Liang,Introduction to Java Programming,revised by Dai-kaiyu 16 Trace Code

17 Liang,Introduction to Java Programming,revised by Dai-kaiyu 17 Trace Code

18 Liang,Introduction to Java Programming,revised by Dai-kaiyu 18 Trace Code

19 Liang,Introduction to Java Programming,revised by Dai-kaiyu 19 Trace Code

20 Liang,Introduction to Java Programming,revised by Dai-kaiyu 20 String Method intern String comparisons  Slow operation  Method intern improves this performance Returns reference to String Guarantees reference has same contents as original String To create a constant object in the memory(const pool) with the same content with the original object. Then it is enough to just compare their references,not concret content.

21 Liang,Introduction to Java Programming,revised by Dai-kaiyu 21 If the String is changed? Class String is immutable  The difference between String s1 = new String(“I am string”); String s2 =new String(“I am string”); String s1 = “I am string”; String s2 = “I am string”;  What about String s = "Hello"; s = s + " world!"; == ? Equals ? If we always change the String, then it will bring bigger memory, change to StringBuffer

22 Liang,Introduction to Java Programming,revised by Dai-kaiyu 22 Finding String Length Finding string length using the length() method: message = "Welcome"; message.length() (returns 7 )

23 Liang,Introduction to Java Programming,revised by Dai-kaiyu 23 Retrieving Individual Characters in a String Do not use message[0] Use message.charAt(index) Index starts from 0 StringIndexOutOfBoundsException

24 Liang,Introduction to Java Programming,revised by Dai-kaiyu 24 String Concatenation String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);

25 Liang,Introduction to Java Programming,revised by Dai-kaiyu 25 Extracting Substrings String is an immutable class; its values cannot be changed individually. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML";

26 Liang,Introduction to Java Programming,revised by Dai-kaiyu 26 String Comparisons equals String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same reference } Demo TestString.java

27 Liang,Introduction to Java Programming,revised by Dai-kaiyu 27 String Comparisons, cont. compareTo(Object object) String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2

28 Liang,Introduction to Java Programming,revised by Dai-kaiyu 28 String Comparisons, cont. equalsIgnoreCase regionMatches: compares portions of two strings for equality str.startsWith(prefix) str.endsWith(suffix)

29 Liang,Introduction to Java Programming,revised by Dai-kaiyu 29 1 // StringCompare.java 2 // This program demonstrates the methods equals, 3 // equalsIgnoreCase, compareTo, and regionMatches 4 // of the String class. 5 6 // Java extension packages 7 import javax.swing.JOptionPane; 8 9 public class StringCompare { 10 11 // test String class comparison methods 12 public static void main( String args[] ) 13 { 14 String s1, s2, s3, s4, output; 15 16 s1 = new String( "hello" ); 17 s2 = new String( "good bye" ); 18 s3 = new String( "Happy Birthday" ); 19 s4 = new String( "happy birthday" ); 20 21 output = "s1 = " + s1 + "\ns2 = " + s2 + 22 "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n"; 23 24 // test for equality 25 if ( s1.equals( "hello" ) ) 26 output += "s1 equals \"hello\"\n"; 27 else 28 output += "s1 does not equal \"hello\"\n"; 29 30 // test for equality with == 31 if ( s1 == "hello" ) 32 output += "s1 equals \"hello\"\n"; 33 else 34 output += "s1 does not equal \"hello\"\n"; 35 Method equals tests two objects for equality using lexicographical comparison Equality operator ( == ) tests if both references refer to same object in memory Compare: s1 = new String(“hello”); s1 = “hello”

30 Liang,Introduction to Java Programming,revised by Dai-kaiyu 30 36 // test for equality (ignore case) 37 if ( s3.equalsIgnoreCase( s4 ) ) 38 output += "s3 equals s4\n"; 39 else 40 output += "s3 does not equal s4\n"; 41 42 // test compareTo 43 output += 44 "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) + 45 "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) + 46 "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) + 47 "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) + 48 "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) + 49 "\n\n"; 50 51 // test regionMatches (case sensitive) 52 if ( s3.regionMatches( 0, s4, 0, 5 ) ) 53 output += "First 5 characters of s3 and s4 match\n"; 54 else 55 output += 56 "First 5 characters of s3 and s4 do not match\n"; 57 58 // test regionMatches (ignore case) 59 if ( s3.regionMatches( true, 0, s4, 0, 5 ) ) 60 output += "First 5 characters of s3 and s4 match"; 61 else 62 output += 63 "First 5 characters of s3 and s4 do not match"; 64 Test two objects for equality, but ignore case of letters in String Method compareTo compares String objects Method regionMatches compares portions of two String objects for equality Ignore case

31 Liang,Introduction to Java Programming,revised by Dai-kaiyu 31 65 JOptionPane.showMessageDialog( null, output, 66 "Demonstrating String Class Constructors", 67 JOptionPane.INFORMATION_MESSAGE ); 68 69 System.exit( 0 ); 70 } 71 72 } // end class StringCompare

32 Liang,Introduction to Java Programming,revised by Dai-kaiyu 32 String Conversions The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods: toLowerCase toUpperCase trim replace(oldChar, newChar)

33 Liang,Introduction to Java Programming,revised by Dai-kaiyu 33 Finding a Character or a Substring in a String "Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('x') returns -1. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java",5) returns 11. "Welcome to Java".indexOf("java",5) returns -1. "Welcome to Java".lastIndexOf('a') returns 14.

34 Liang,Introduction to Java Programming,revised by Dai-kaiyu 34 Conversion between String and Arrays toCharArray() char [] chars = “Java”.toCharArray(); getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) char[] dst = {‘J’, ’A’, ‘V’, ‘A’, ‘1’, ‘3’, ‘0’, ‘1’}; “CS3720”.getChars(2, 6, dst, 4); Dst = { ‘J’, ’A’, ‘V’, ‘A’, ‘3’, ‘7’, ‘2’, ‘0’ }

35 Liang,Introduction to Java Programming,revised by Dai-kaiyu 35 Convert Character and Numbers to Strings The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name valueOf with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.

36 Liang,Introduction to Java Programming,revised by Dai-kaiyu 36 1 // Fig. 10.10: StringValueOf.java 2 // This program demonstrates the String class valueOf methods. 3 4 // Java extension packages 5 import javax.swing.*; 6 7 public class StringValueOf { 8 9 // test String valueOf methods 10 public static void main( String args[] ) 11 { 12 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 13 boolean b = true; 14 char c = 'Z'; 15 int i = 7; 16 long l = 10000000; 17 float f = 2.5f; 18 double d = 33.333; 19 20 Object o = "hello"; // assign to an Object reference 21 String output; 22 23 output = "char array = " + String.valueOf( charArray ) + 24 "\npart of char array = " + 25 String.valueOf( charArray, 3, 3 ) + 26 "\nboolean = " + String.valueOf( b ) + 27 "\nchar = " + String.valueOf( c ) + 28 "\nint = " + String.valueOf( i ) + 29 "\nlong = " + String.valueOf( l ) + 30 "\nfloat = " + String.valueOf( f ) + 31 "\ndouble = " + String.valueOf( d ) + 32 "\nObject = " + String.valueOf( o ); 33 static method valueOf of class String returns String representation of various types

37 Liang,Introduction to Java Programming,revised by Dai-kaiyu 37 34 JOptionPane.showMessageDialog( null, output, 35 "Demonstrating String Class valueOf Methods", 36 JOptionPane.INFORMATION_MESSAGE ); 37 38 System.exit( 0 ); 39 } 40 41 } // end class StringValueOf

38 Liang,Introduction to Java Programming,revised by Dai-kaiyu 38 Example 7.1 Finding Palindromes Objective: Checking whether a string is a palindrome: a string that reads the same forward and backward. CheckPalindrome Run

39 Liang,Introduction to Java Programming,revised by Dai-kaiyu 39 Character Class Examples Treat primitive variables as objects  Type wrapper classes Boolean Character Double Float Byte Short Integer Long  We examine class Character

40 Liang,Introduction to Java Programming,revised by Dai-kaiyu 40 Type-Wrapper Classes for Primitive Types Type-wrapper class  Each primitive type has one Character, Byte, Integer, Short, Boolean, Long, Float, Double, etc.  Enable to represent primitive as Object Primitive data types can be processed polymorphically  Declared as final,inherited from Number(except for Boolean, Character)  Many methods are declared static

41 Liang,Introduction to Java Programming,revised by Dai-kaiyu 41 The Character Class

42 Liang,Introduction to Java Programming,revised by Dai-kaiyu 42 Examples Character charObject = new Character('b'); charObject.charValue() returns ‘b’; charObject.compareTo(new Character('a')) returns 1 charObject.compareTo(new Character('b')) returns 0 charObject.compareTo(new Character('c')) returns -1 charObject.compareTo(new Character('d') returns –2 charObject.equals(new Character('b')) returns true charObject.equals(new Character('d')) returns false

43 Liang,Introduction to Java Programming,revised by Dai-kaiyu 43 Examples Suppose c is variable of a char type Character.isDefined( c ) Character.isDigit( c ) Character.isJavaIdentifierStart( c ) Character.isJavaIdentifierPart( c ) Character.isLetter( c ) Character.isLetterOrDigit( c ) Character.isLowerCase( c ) Character.isUpperCase( c ) Character.toUpperCase( c ) Character.toLowerCase( c )

44 Liang,Introduction to Java Programming,revised by Dai-kaiyu 44 Example 7.2 Counting Each Letter in a String This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. CountEachLetter Run

45 Liang,Introduction to Java Programming,revised by Dai-kaiyu 45 The StringBuffer Class The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used. StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer. However, the value of a String object is fixed once the string is created.

46 Liang,Introduction to Java Programming,revised by Dai-kaiyu 46

47 Liang,Introduction to Java Programming,revised by Dai-kaiyu 47 StringBuffer Constructors public StringBuffer() No characters, initial capacity 16 characters. public StringBuffer(int length) No characters, initial capacity specified by the length argument. public StringBuffer(String str) Represents the same sequence of characters as the string argument. Initial capacity 16 plus the length of the string argument.

48 Liang,Introduction to Java Programming,revised by Dai-kaiyu 48 1 // Fig. 10.12: StringBufferConstructors.java 2 // This program demonstrates the StringBuffer constructors. 3 4 // Java extension packages 5 import javax.swing.*; 6 7 public class StringBufferConstructors { 8 9 // test StringBuffer constructors 10 public static void main( String args[] ) 11 { 12 StringBuffer buffer1, buffer2, buffer3; 13 14 buffer1 = new StringBuffer(); 15 buffer2 = new StringBuffer( 10 ); 16 buffer3 = new StringBuffer( "hello" ); 17 18 String output = 19 "buffer1 = \"" + buffer1.toString() + "\"" + 20 "\nbuffer2 = \"" + buffer2.toString() + "\"" + 21 "\nbuffer3 = \"" + buffer3.toString() + "\""; 22 23 JOptionPane.showMessageDialog( null, output, 24 "Demonstrating StringBuffer Class Constructors", 25 JOptionPane.INFORMATION_MESSAGE ); 26 27 System.exit( 0 ); 28 } 29 30 } // end class StringBufferConstructors Default constructor creates empty StringBuffer with capacity of 16 characters Second constructor creates empty StringBuffer with capacity of specified ( 10 ) characters Third constructor creates StringBuffer with String “ hello ” and capacity of 16 characters Method toString returns String representation of StringBuffer

49 Liang,Introduction to Java Programming,revised by Dai-kaiyu 49 StringBuffer Methods Method length  Return StringBuffer length Method capacity  Return StringBuffer capacity(the number can further contain) Method setLength  Increase or decrease StringBuffer length Method toString  Return the number of characters actually stored in the string buffer.

50 Liang,Introduction to Java Programming,revised by Dai-kaiyu 50 StringBuffer Methods Manipulating StringBuffer characters  Method charAt Return StringBuffer character at specified index  Method setCharAt Set StringBuffer character at specified index  Method getChars Return character array from StringBuffer  Method reverse Reverse StringBuffer contents

51 Liang,Introduction to Java Programming,revised by Dai-kaiyu 51 1 // StringBufferChars.java 2 // The charAt, setCharAt, getChars, and reverse methods 3 // of class StringBuffer. 4 5 // Java extension packages 6 import javax.swing.*; 7 8 public class StringBufferChars { 9 10 // test StringBuffer character methods 11 public static void main( String args[] ) 12 { 13 StringBuffer buffer = new StringBuffer( "hello there" ); 14 15 String output = "buffer = " + buffer.toString() + 16 "\nCharacter at 0: " + buffer.charAt( 0 ) + 17 "\nCharacter at 4: " + buffer.charAt( 4 ); 18 19 char charArray[] = new char[ buffer.length() ]; 20 buffer.getChars( 0, buffer.length(), charArray, 0 ); 21 output += "\n\nThe characters are: "; 22 23 for ( int count = 0; count < charArray.length; ++count ) 24 output += charArray[ count ]; 25 26 buffer.setCharAt( 0, 'H' ); 27 buffer.setCharAt( 6, 'T' ); 28 output += "\n\nbuf = " + buffer.toString(); 29 30 buffer.reverse(); 31 output += "\n\nbuf = " + buffer.toString(); 32 Return StringBuffer characters at indices 0 and 4, respectively Return character array from StringBuffer Replace characters at indices 0 and 6 with ‘ H ’ and ‘ T,’ respectively Reverse characters in StringBuffer

52 Liang,Introduction to Java Programming,revised by Dai-kaiyu 52 33 JOptionPane.showMessageDialog( null, output, 34 "Demonstrating StringBuffer Character Methods", 35 JOptionPane.INFORMATION_MESSAGE ); 36 37 System.exit( 0 ); 38 } 39 40 } // end class StringBufferChars

53 Liang,Introduction to Java Programming,revised by Dai-kaiyu 53 Appending New Contents into a String Buffer StringBuffer strBuf = new StringBuffer(); strBuf.append("Welcome"); strBuf.append(' '); strBuf.append("to"); strBuf.append(' '); strBuf.append("Java");

54 Liang,Introduction to Java Programming,revised by Dai-kaiyu 54 1 // StringBufferAppend.java 2 // This program demonstrates the append 3 // methods of the StringBuffer class. 4 5 // Java extension packages 6 import javax.swing.*; 7 8 public class StringBufferAppend { 9 10 // test StringBuffer append methods 11 public static void main( String args[] ) 12 { 13 Object o = "hello"; 14 String s = "good bye"; 15 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 16 boolean b = true; 17 char c = 'Z'; 18 int i = 7; 19 long l = 10000000; 20 float f = 2.5f; 21 double d = 33.333; 22 StringBuffer buffer = new StringBuffer(); 23 24 buffer.append( o ); 25 buffer.append( " " ); 26 Append String “ hello ” to StringBuffer

55 Liang,Introduction to Java Programming,revised by Dai-kaiyu 55 27 buffer.append( s ); 28 buffer.append( " " ); 29 buffer.append( charArray ); 30 buffer.append( " " ); 31 buffer.append( charArray, 0, 3 ); 32 buffer.append( " " ); 33 buffer.append( b ); 34 buffer.append( " " ); 35 buffer.append( c ); 36 buffer.append( " " ); 37 buffer.append( i ); 38 buffer.append( " " ); 39 buffer.append( l ); 40 buffer.append( " " ); 41 buffer.append( f ); 42 buffer.append( " " ); 43 buffer.append( d ); 44 45 JOptionPane.showMessageDialog( null, 46 "buffer = " + buffer.toString(), 47 "Demonstrating StringBuffer append Methods", 48 JOptionPane.INFORMATION_MESSAGE ); 49 50 System.exit( 0 ); 51 } 52 53 } // end StringBufferAppend Append String “ good bye ”Append “ a b c d e f ”Append “ a b c ” Append boolean, char, int, long, float and double

56 Liang,Introduction to Java Programming,revised by Dai-kaiyu 56 StringBuffer Insertion and Deletion Methods Method insert  Allow data-type values to be inserted into StringBuffer Methods delete and deleteCharAt  Allow characters to be removed from StringBuffer

57 Liang,Introduction to Java Programming,revised by Dai-kaiyu 57 1 // Fig. 10.16: StringBufferInsert.java 2 // This program demonstrates the insert and delete 3 // methods of class StringBuffer. 4 5 // Java extension packages 6 import javax.swing.*; 7 8 public class StringBufferInsert { 9 10 // test StringBuffer insert methods 11 public static void main( String args[] ) 12 { 13 Object o = "hello"; 14 String s = "good bye"; 15 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 16 boolean b = true; 17 char c = 'K'; 18 int i = 7; 19 long l = 10000000; 20 float f = 2.5f; 21 double d = 33.333; 22 StringBuffer buffer = new StringBuffer(); 23

58 Liang,Introduction to Java Programming,revised by Dai-kaiyu 58 24 buffer.insert( 0, o ); 25 buffer.insert( 0, " " ); 26 buffer.insert( 0, s ); 27 buffer.insert( 0, " " ); 28 buffer.insert( 0, charArray ); 29 buffer.insert( 0, " " ); 30 buffer.insert( 0, b ); 31 buffer.insert( 0, " " ); 32 buffer.insert( 0, c ); 33 buffer.insert( 0, " " ); 34 buffer.insert( 0, i ); 35 buffer.insert( 0, " " ); 36 buffer.insert( 0, l ); 37 buffer.insert( 0, " " ); 38 buffer.insert( 0, f ); 39 buffer.insert( 0, " " ); 40 buffer.insert( 0, d ); 41 42 String output = 43 "buffer after inserts:\n" + buffer.toString(); 44 45 buffer.deleteCharAt( 10 ); // delete 5 in 2.5 46 buffer.delete( 2, 6 ); // delete.333 in 33.333 47 48 output += 49 "\n\nbuffer after deletes:\n" + buffer.toString(); 50 51 JOptionPane.showMessageDialog( null, output, 52 "Demonstrating StringBufferer Inserts and Deletes", 53 JOptionPane.INFORMATION_MESSAGE ); 54 55 System.exit( 0 ); 56 } 57 58 } // end class StringBufferInsert Use method insert to insert data types in beginning of StringBuffer Use method deleteCharAt to remove character from index 10 in StringBuffer Remove characters from indices 2 through 5 (inclusive)

59 Liang,Introduction to Java Programming,revised by Dai-kaiyu 59

60 Liang,Introduction to Java Programming,revised by Dai-kaiyu 60 StringBuilder Newly introduced in J2SE 5.0 Almost the same function with StringBuffer Do not deal with Synchronized, so has better efficiency, compared with StringBuffer When frequently concatenate string, StringBuilder and StringBuffer is more efficient than String Demo TestAppendStringTime.java

61 Liang,Introduction to Java Programming,revised by Dai-kaiyu 61 Example 7.3 Checking Palindromes Ignoring Non- alphanumeric Characters PalindromeIgnoreNonAlphanumeric Run

62 Liang,Introduction to Java Programming,revised by Dai-kaiyu 62 Class StringTokenizer Tokenizer  Partition String into individual substrings  Use delimiter  Java offers java.util.StringTokenizer

63 Liang,Introduction to Java Programming,revised by Dai-kaiyu 63 The StringTokenizer Class

64 Liang,Introduction to Java Programming,revised by Dai-kaiyu 64 Examples 1 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s); System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays The total number of tokens is 3 Java is cool.

65 Liang,Introduction to Java Programming,revised by Dai-kaiyu 65 Examples 2 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s, "ac"); System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays The total number of tokens is 4 J v is ool.

66 Liang,Introduction to Java Programming,revised by Dai-kaiyu 66 Examples 3 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s, "ac", ture); System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays The total number of tokens is 7 J a v a is c ool. Delimiters counted as tokens

67 Liang,Introduction to Java Programming,revised by Dai-kaiyu 67 No no-arg Constructor in StringTokenizer The StringTokenizer class does not have a no-arg constructor. Normally it is a good programming practice to provide a no-arg constructor for each class. On rare occasions, however, a no-arg constructor does not make sense. StringTokenizer is such an example. A StringTokenizer object must be created for a string, which should be passed as an argument from a constructor.

68 Liang,Introduction to Java Programming,revised by Dai-kaiyu 68 The Scanner Class The delimiters are single characters in StringTokenizer. You can use the new JDK 1.5 java.util.Scanner class to specify a word as a delimiter. JDK 1.5 Feature String s = "Welcome to Java! Java is fun! Java is cool!"; Scanner scanner = new Scanner(s); scanner.useDelimiter("Java"); while (scanner.hasNext()) System.out.println(scanner.next()); Creates an instance of Scanner for the string. Sets “Java” as a delimiter. hasNext() returns true if there are still more tokens left. The next() method returns a token as a string. Welcome to ! is fun! is cool! Output

69 Liang,Introduction to Java Programming,revised by Dai-kaiyu 69 Scanning Primitive Type Values If a token is a primitive data type value, you can use the methods nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain it. For example, the following code adds all numbers in the string. Note that the delimiter is space by default. JDK 1.5 Feature String s = "1 2 3 4"; Scanner scanner = new Scanner(s); int sum = 0; while (scanner.hasNext()) sum += scanner.nextInt(); System.out.println("Sum is " + sum); scanner.next().chatAt(0) get the char

70 Liang,Introduction to Java Programming,revised by Dai-kaiyu 70 Console Input Using Scanner Another important application of the Scanner class is to read input from the console. JDK 1.5 Feature System.out.print("Please enter an int value: "); Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); NOTE: StringTokenizer can specify several single characters as delimiters. Scanner can use a single character or a word as the delimiter. So, if you need to scan a string with multiple single characters as delimiters, use StringTokenizer. If you need to use a word as the delimiter, use Scanner.

71 Liang,Introduction to Java Programming,revised by Dai-kaiyu 71 Command-Line Parameters In the main method, get the arguments from args[0], args[1],..., args[n], which corresponds to arg0, arg1,..., argn in the command line. class TestMain { public static void main(String[] args) {... } java TestMain arg0 arg1 arg2... argn

72 Liang,Introduction to Java Programming,revised by Dai-kaiyu 72 Example 7.4 Using Command-Line Parameters Objective: Write a program that will perform binary operations on integers. The program receives three parameters: an operator and two integers. Calculator java Calculator 2 + 3 java Calculator 2 - 3 Run java Calculator 2 / 3 java Calculator 2 “*” 3


Download ppt "Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live."

Similar presentations


Ads by Google