Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Similar presentations


Presentation on theme: "Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class."— Presentation transcript:

1 Chapter 10 - Strings and Characters

2 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class StringTokenizer ( java.util ) –Techniques used here appropriate for making word processors, text editors, page layout software

3 10.2Fundamentals of Characters and Strings Characters –Character constant - integer represented as a character in single quotes (Unicode character set) 'z' is integer value of z Strings –Group of characters treated as a single unit –May include letters, digits, special characters ( +, - *...) –Strings are objects of class String

4 10.2Fundamentals of Characters and Strings Strings (continued) –String literal (string constants or anonymous String objects) Sequence of characters written in double quotes "John Q. Doe" or "111222333" Java treats all anonymous String objects with same contents as one object with many references –Assigning strings May assign in declaration String color = "blue"; color is a String reference

5 10.3 String Constructors Constructors for class String –s1 = new String() s1 is an empty string –s2 = new String( anotherString ) s2 is a copy of anotherString –s3 = new String( charArray ) s3 contains all the characters in charArray –s4 = new String( charArray, offset, numElements ) s4 contains numElements characters from charArray, starting at location offset –s5 = new String( byteArray, offset, numElements) As above, but with a byteArray

6 10.3 String Constructors Constructors for class String –s6 = new String( byteArray ) s6 contains copy of entire byteArray StringBuffer –Dynamically resizable, modifiable string (more later) –StringBuffer buffer = new StringBuffer( "Hello there" ); –Can initialize Strings with StringBuffer s s7 = new String( myStringBuffer )

7 Class StringConstructors 1. main 1.1 Initialize arrays 1.2 Declarations 1.3 Constructors 1// Fig. 10.1: StringConstructors.java 2// This program demonstrates the String class constructors. 3import javax.swing.*; 4 5public class StringConstructors { 6 public static void main( String args[] ) 7 { 8 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 9 'd', 'a', 'y' }; 10 byte byteArray[] = { (byte) 'n', (byte) 'e', (byte) 'w', 11 (byte) ' ', (byte) 'y', (byte) 'e', 12 (byte) 'a', (byte) 'r' }; 13 StringBuffer buffer; 14 String s, s1, s2, s3, s4, s5, s6, s7, output; 15 16 17 s = new String( "hello" ); 18 buffer = 19 new StringBuffer( "Welcome to Java Programming!" ); 20 21 // use the String constructors 22 s1 = new String(); 23 s2 = new String( s ); 24 s3 = new String( charArray ); 25 s4 = new String( charArray, 6, 3 ); 26 s5 = new String( byteArray, 4, 4 ); 27 s6 = new String( byteArray ); 28 s7 = new String( buffer ); 29

8 2. Append output 3. GUI Program Output 30 output = "s1 = " + s1 + 31 "\ns2 = " + s2 + 32 "\ns3 = " + s3 + 33 "\ns4 = " + s4 + 34 "\ns5 = " + s5 + 35 "\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}

9 10.4 String Methods length, charAt and getChars String methods –s1.length() Returns length of string Be careful, String s do not have an instance variable length like arrays –s1.length is an error –s1.charAt( index ) Returns char at location index Numbered like arrays (start at position 0 ) –s1.getChars( start, end, charArray, offset ) Copies characters in s1 from index start to index end to location offset in charArray

10 Class StringMisc 1. main 1.1 Initialization 1.2 Output 2. s1.length() 3. Loop and print reversed characters 1// Fig. 10.2: StringMisc.java 2// This program demonstrates the length, charAt and getChars 3// methods of the String class. 4// 5// Note: Method getChars requires a starting point 6// and ending point in the String. The starting point is the 7// actual subscript from which copying starts. The ending point 8// is one past the subscript at which the copying ends. 9import javax.swing.*; 10 11public class StringMisc { 12 public static void main( String args[] ) 13 { 14 String s1, output; 15 char charArray[]; 16 17 s1 = new String( "hello there" ); 18 charArray = new char[ 5 ]; 19 20 // output the string 21 output = "s1: " + s1; 22 23 // test the length method 24 output += "\nLength of s1: " + s1.length(); 25 26 // loop through the characters in s1 and display reversed 27 output += "\nThe string reversed is: "; 28 29 for ( int i = s1.length() - 1; i >= 0; i-- ) 30 output += s1.charAt( i ) + " ";

11 4. getChars 5. GUI Program Output 34 s1.getChars( 0, 5, charArray, 0 ); 35 output += "\nThe character array is: "; 36 37 for ( int i = 0; i < charArray.length; i++ ) 38 output += charArray[ i ]; 39 40 JOptionPane.showMessageDialog( null, output, 41 "Demonstrating String Class Constructors", 42 JOptionPane.INFORMATION_MESSAGE ); 43 44 System.exit( 0 ); 45 } 46} 33 // copy characters from string into char array

12 10.5Comparing String s Comparing String s –All characters represented as numeric codes (Appendix D) –When computer compares strings, compares numeric codes Lexicographical comparison - compare Unicode values Lowercase different than uppercase Comparison methods –s1.equals( "Hi" ) Returns true if s1 equal to "Hi" Capitalization (case) matters –s1.equalsIgnoreCase( otherString ) Tests for equality, case does not matter "hello" equal to "HELLO"

13 10.5Comparing String s Comparison methods –s1.compareTo( otherString ) Uses lexicographical comparison Returns 0 if strings equal Returns negative number if s1 < otherString Returns positive number if s1 > otherString –s1.regionMatches( offset, otherString, start, end ) Compares s1 from location offset to otherString from location start to end –s1.regionMatches( ignoreCase, offset, otherString, start, end ) As above, but if ignoreCase is true, case is ignored

14 10.5Comparing String s == operator –When used with primitive data types, returns true if equal –When used with references, returns true if point to same location in memory –Remember, Java treats all anonymous String objects with same contents as one object with many references s1 = "hello"; //uses anonymous object s2 = new String( "hello" ); s1 == "hello"; //true s2 == "hello"; //false

15 29 else Class StringCompare 1. main 1.1 Initialization 1.2 Append output 2. Tests for equality 1// Fig. 10.3: StringCompare 2// This program demonstrates the methods equals, 3// equalsIgnoreCase, compareTo, and regionMatches 4// of the String class. 5import javax.swing.JOptionPane; 6 7public class StringCompare { 8 public static void main( String args[] ) 9 { 10 String s1, s2, s3, s4, output; 11 12 s1 = new String( "hello" ); 13 s2 = new String( "good bye" ); 14 s3 = new String( "Happy Birthday" ); 15 s4 = new String( "happy birthday" ); 16 17 output = "s1 = " + s1 + "\ns2 = " + s2 + 18 "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n"; 19 20 // test for equality 21 if ( s1.equals( "hello" ) ) 22 output += "s1 equals \"hello\"\n"; 23 else 24 output += "s1 does not equal \"hello\"\n"; 25 26 // test for equality with == 27 27 if ( s1 == "hello" ) 28 output += "s1 equals \"hello\"\n"; 30 output += "s1 does not equal \"hello\"\n"; s1 will fail this test because it was not initialized with an anonymous String object.

16 2. Tests for equality 3. compareTo 4. regionMatches 31 32 // test for equality--ignore case 33 if ( s3.equalsIgnoreCase( s4 ) ) 34 output += "s3 equals s4\n"; 35 else 36 output += "s3 does not equal s4\n"; 37 38 // test compareTo 39 output += 40 "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) + 41 "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) + 42 "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) + 43 "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) + 44 "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) + 45 "\n\n"; 46 47 // test regionMatches (case sensitive) 48 if ( s3.regionMatches( 0, s4, 0, 5 ) ) 49 output += "First 5 characters of s3 and s4 match\n"; 50 else 51 output += 52 "First 5 characters of s3 and s4 do not match\n"; 53 54 // test regionMatches (ignore case) 55 if ( s3.regionMatches( true, 0, s4, 0, 5 ) ) 56 output += "First 5 characters of s3 and s4 match"; 57 else 58 output += 59 "First 5 characters of s3 and s4 do not match"; 60

17 5. GUI Program Output 61 JOptionPane.showMessageDialog( null, output, 62 "Demonstrating String Class Constructors", 63 JOptionPane.INFORMATION_MESSAGE ); 64 65 System.exit( 0 ); 66 } 67} Using equals, ==, and equalsIgnoreCase

18 10.6 String Method hashCode Hash table –Fast access to data –Stores information using a calculation that makes a hash code Code used to choose location to store object in table –To retrieve information, use same calculation Hash code determined, go to that location of table Get original value –Every object can be stored in a hash table –Class Object defines method hashCode Inherited by all subclasses hashCode overridden in class String to provide a good hash code distribution

19 Class StringHashCode 1. main 1.1 Initialization 2. hashCode 3. GUI Program Output 1// Fig. 10.5: StringHashCode.java1 2// This program demonstrates the method 3// hashCode of the String class. 4import javax.swing.*; 5 6public class StringHashCode { 7 public static void main( String args[] ) 8 { 9 String s1 = "hello", 10 s2 = "Hello"; 11 12 String output = 13 "The hash code for \"" + s1 + "\" is " + 14 s1.hashCode() + 15 "\nThe hash code for \"" + s2 + "\" is " + 16 s2.hashCode(); 17 18 JOptionPane.showMessageDialog( null, output, 19 "Demonstrating String Method hashCode", 20 JOptionPane.INFORMATION_MESSAGE ); 21 22 System.exit( 0 ); 23 } 24}

20 10.7Locating Characters and Substrings in String s Search methods –s1.indexOf( integerRep ) integerRep - integer representation of a character ( 'z' ) Returns index of the first occurrence of the character in the string –Returns -1 if not found –s1.indexOf( integerRep, startSearch ) As above, but begins search at position startSearch –s1.lastIndexOf( integerRep ) Returns index of last occurrence of character in string –s1.lastIndexOf( integerRep, startSearch ) As above, but searches backwards from position startSearch

21 10.7Locating Characters and Substrings in String s Search methods (continued) –Can use indexOf and lastIndexOf with String s –Search for substrings within a string Identical usage as with characters, i.e. s1.indexOf( "hi" ) s1.lastIndexOf( "this", 24 )

22 Class StringIndexMethods 1. main 1.1 Initialization 2. indexOf (two versions) 3. lastIndexOf (two versions) 1// Fig. 10.6: StringIndexMethods.java 2// This program demonstrates the String 3// class index methods. 4import javax.swing.*; 5 6 7public class StringIndexMethods { 8 public static void main( String args[] ) 9 { 10 String letters = "abcdefghijklmabcdefghijklm"; 11 String output; 12 13 // test indexOf to locate a character in a string 14 output = "'c' is located at index " + 15 letters.indexOf( 'c' ); 16 17 output += "\n'a' is located at index " + 18 letters.indexOf( 'a', 1 ); 19 20 output += "\n'$' is located at index " + 21 letters.indexOf( '$' ); 22 23 // test lastIndexOf to find a character in a string 24 output += "\n\nLast 'c' is located at index " + 25 letters.lastIndexOf( 'c' ); 26 27 output += "\nLast 'a' is located at index " + 28 letters.lastIndexOf( 'a', 25 ); 29

23 4. indexOf (two versions) 5. lastIndexOf (two versions) 6. GUI 30 output += "\nLast '$' is located at index " + 31 letters.lastIndexOf( '$' ); 32 33 // test indexOf to locate a substring in a string 34 output += "\n\n\"def\" is located at index " + 35 letters.indexOf( "def" ); 36 37 output += "\n\"def\" is located at index " + 38 letters.indexOf( "def", 7 ); 39 40 output += "\n\"hello\" is located at index " + 41 letters.indexOf( "hello" ); 42 43 // test lastIndexOf to find a substring in a string 44 output += "\n\nLast \"def\" is located at index " + 45 letters.lastIndexOf( "def" ); 46 47 output += "\nLast \"def\" is located at index " + 48 letters.lastIndexOf( "def", 25 ); 49 50 output += "\nLast \"hello\" is located at index " + 51 letters.lastIndexOf( "hello" ); 52 53 JOptionPane.showMessageDialog( null, output, 54 "Demonstrating String Class \"index\" Methods", 55 JOptionPane.INFORMATION_MESSAGE ); 56 57 System.exit( 0 ); 58 } 59} 60

24 Program Output

25 10.8Extracting Substrings from String s substring methods –Return a String object –s1.substring( startIndex ) Returns a substring from startIndex to the end of the string –s1.substring( start, end ) Returns a substring from location start up to, but not including, location end –If index out of bounds, StringIndexOutOfBoundsException generated

26 Class Substring 1. main 1.1 Initialization 2. substring methods 3. GUI Program Output 1// Fig. 10.7: SubString.java 2// This program demonstrates the 3// String class substring methods. 4import javax.swing.*; 5 6public class SubString { 7 public static void main( String args[] ) 8 { 9 String letters = "abcdefghijklmabcdefghijklm"; 10 String output; 11 12 // test substring methods 13 output = "Substring from index 20 to end is " + 14 "\"" + letters.substring( 20 ) + "\"\n"; 15 16 output += "Substring from index 0 up to 6 is " + 17 "\"" + letters.substring( 0, 6 ) + "\""; 18 19 JOptionPane.showMessageDialog( null, output, 20 "Demonstrating String Class Substring Methods", 21 JOptionPane.INFORMATION_MESSAGE ); 22 23 System.exit( 0 ); 24 } 25}

27 10.9Concatenating String s Method concat –Concatenates two String s, returns new String object –Original String s are not modified –s1.concat( s2 ) Returns concatenation of s1 and s2 If no argument, returns s1

28 Class StringConcat 1. main 1.1 Initialization 2. concat 3. GUI 1// Fig. 10.8: StringConcat.java 2// This program demonstrates the String class concat method. 3// Note that the concat method returns a new String object. It 4// does not modify the object that invoked the concat method. 5import javax.swing.*; 6 7public class StringConcat { 8 public static void main( String args[] ) 9 { 10 String s1 = new String( "Happy " ), 11 s2 = new String( "Birthday" ), 12 output; 13 14 output = "s1 = " + s1 + 15 "\ns2 = " + s2; 16 17 output += "\n\nResult of s1.concat( s2 ) = " + 18 s1.concat( s2 ); 19 20 output += "\ns1 after concatenation = " + s1; 21 22 JOptionPane.showMessageDialog( null, output, 23 "Demonstrating String Method concat", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 } 28}

29 Program Output

30 10.10 Miscellaneous String Methods Miscellaneous methods –s1.replace( char1, char2 ) Returns a new String, replacing all instances of char1 with char2 –Use integer representations: 'z', '1', etc. –Original String not changed If no instances of char1, original string returned –s1.toUpperCase() Returns new String object with all letters capitalized –If no changes needed, original string returned Original string unchanged s1.toLowerCase() similar

31 10.10 Miscellaneous String Methods Miscellaneous methods (continued) –s1.trim() Returns new String, removing all whitespace characters at beginning or end Original unchanged –s1.toString() All objects can be converted to String s with toString –s1.toCharArray() Creates a new character array containing copy of characters in s1

32 Class StringMisc2 1. main 1.1 Initialization 2. replace 3. toUpperCase and toLowerCase 4. trim 1// Fig. 10.9: StringMisc2.java 2// This program demonstrates the String methods replace, 3// toLowerCase, toUpperCase, trim, toString and toCharArray 4import javax.swing.*; 5 6public class StringMisc2 { 7 public static void main( String args[] ) 8 { 9 String s1 = new String( "hello" ), 10 s2 = new String( "GOOD BYE" ), 11 s3 = new String( " spaces " ), 12 output; 13 14 output = "s1 = " + s1 + 15 "\ns2 = " + s2 + 16 "\ns3 = " + s3; 17 18 // test method replace 19 output += "\n\nReplace 'l' with 'L' in s1: " + 20 s1.replace( 'l', 'L' ); 21 22 // test toLowerCase and toUpperCase 23 output += 24 "\n\ns1.toUpperCase() = " + s1.toUpperCase() + 25 "\ns2.toLowerCase() = " + s2.toLowerCase(); 26 27 // test trim method 28 output += "\n\ns3 after trim = \"" + s3.trim() + "\""; 29

33 5. toString 6. toCharArray 7. GUI 30 // test toString method 31 output += "\n\ns1 = " + s1.toString(); 32 33 // test toCharArray method 34 char charArray[] = s1.toCharArray(); 35 36 output += "\n\ns1 as a character array = "; 37 38 for ( int i = 0; i < charArray.length; ++i ) 39 output += charArray[ i ]; 40 41 JOptionPane.showMessageDialog( null, output, 42 "Demonstrating Miscellaneous String Methods", 43 JOptionPane.INFORMATION_MESSAGE ); 44 45 System.exit( 0 ); 46 } 47 }

34 Program Output

35 10.11 Using String Method valueOf static methods of class String –Take arguments and convert them to String s –String.valueOf( charArray ) Returns new String object containing characters in charArray –String.valueOf( charArray, startIndex, numChars ) As above, but starts from position startIndex and copies numChars characters –Other versions of valueOf take boolean, char, int, long, float, double, and Object Objects converted to Strings with toString

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

37 3. GUI Program Output 30 JOptionPane.showMessageDialog( null, output, 31 "Demonstrating String Class valueOf Methods", 32 JOptionPane.INFORMATION_MESSAGE ); 33 34 System.exit( 0 ); 35 } 36}

38 10.12 String Method intern Method intern –Improves string comparison performance –Returns reference guaranteed to have same contents Multiple intern s generate references to same object –String s can be compared with == (same location in memory) instead of equals Much faster than comparing character by character

39 Class StringIntern 1. main 1.1 Initialization 2. Comparisons using == 2.1 Comparisons using equals 1// Fig. 10.11: StringIntern.java 2// This program demonstrates the intern method 3// of the String class. 4import javax.swing.*; 5 6public class StringIntern { 7 public static void main( String args[] ) 8 { 9 String s1, s2, s3, s4, output; 10 11 s1 = new String( "hello" ); 12 s2 = new String( "hello" ); 13 14 // Test strings to determine if they are the same 15 // String object in memory. 16 if ( s1 == s2 ) 17 output = 18 "s1 and s2 are the same object in memory"; 19 else 20 output = 21 "s1 and s2 are not the same object in memory"; 22 23 // Test strings for equality of contents 24 if ( s1.equals( s2 ) ) 25 output += "\ns1 and s2 are equal"; 26 else 27 output += "\ns1 and s2 are not equal"; 28

40 3. intern 4. Comparisons using == 29 // Use String intern method to get a unique copy of 30 // "hello" referred to by both s3 and s4. 31 31 s3 = s1.intern(); 32 s4 = s2.intern(); 33 34 35 // Test strings to determine if they are the same 36 // String object in memory. 37 if ( s3 == s4 ) 38 output += 39 "\ns3 and s4 are the same object in memory"; 40 else 41 output += 42 "\ns3 and s4 are not the same object in memory"; 43 44 // Determine if s1 and s3 refer to the same object 45 if ( s1 == s3 ) 46 output += 47 "\ns1 and s3 are the same object in memory"; 48 else 49 output += 50 "\ns1 and s3 are not the same object in memory"; 51 52 // Determine if s2 and s4 refer to the same object 53 if ( s2 == s4 ) 54 output += 55 "\ns2 and s4 are the same object in memory"; 56 else 57 output += 58 "\ns2 and s4 are not the same object in memory"; 59 Because s1 and s2 have the same contents, s3 and s4 are references to the same object in memory.

41 4. Comparisons using == 5. GUI Program Output 60 // Determine if s1 and s4 refer to the same object 61 if ( s1 == s4 ) 62 output += 63 "\ns1 and s4 are the same object in memory"; 64 else 65 output += 66 "\ns1 and s4 are not the same object in memory"; 67 68 JOptionPane.showMessageDialog( null, output, 69 "Demonstrating String Method intern", 70 JOptionPane.INFORMATION_MESSAGE ); 71 72 System.exit( 0 ); 73 } 74} 75 s1 and s2 both contain "hello" but are not the same object. s3 and s4 were interned from s1 and s2, and are the same object in memory.

42 10.13 StringBuffer Class Class String –Once a String is created, it cannot be changed Class StringBuffer –Can create modifiable String s –Capable of storing number of characters specified by capacity If capacity exceeded, automatically expands to hold new characters –Can use + and += operators

43 10.14 StringBuffer Constructors StringBuffer constructors –buf1 = new StringBuffer(); Creates empty StringBuffer, capacity of 16 characters –buf2 = new StringBuffer( capacity ); Creates empty StringBuffer with specified capacity –but3 = new StringBuffer( myString ); Creates a StringBuffer containing myString, with capacity myString.length() + 16

44 Class StringBuffer Constructors 1. main 1.1 Initialization (note use of constructors) 2. Output 3. GUI 1// Fig. 10.12: StringBufferConstructors.java 2// This program demonstrates the StringBuffer constructors. 3import javax.swing.*; 4 5public class StringBufferConstructors { 6 public static void main( String args[] ) 7 { 8 StringBuffer buf1, buf2, buf3; 9 10 buf1 = new StringBuffer(); 11 buf2 = new StringBuffer( 10 ); 12 buf3 = new StringBuffer( "hello" ); 13 14 String output = 15 "buf1 = " + "\"" + buf1.toString() + "\"" + 16 "\nbuf2 = " + "\"" + buf2.toString() + "\"" + 17 "\nbuf3 = " + "\"" + buf3.toString() + "\""; 18 19 JOptionPane.showMessageDialog( null, output, 20 "Demonstrating StringBuffer Class Constructors", 21 JOptionPane.INFORMATION_MESSAGE ); 22 23 System.exit( 0 ); 24 } 25}

45 Program Output

46 10.15 StringBuffer Methods length, capacity, setLength and ensureCapacity StringBuffer methods –length - returns length –capacity - returns capacity –setLength( newLength ) Changes length of StringBuffer to newLength If too long, truncates excess characters If too short, fills with null character (numeric representation of 0) –ensureCapacity( size ) Expands capacity to a minimum of size If size less than current capacity, then capacity is unchanged

47 Class StringBufferCapLen 1. main 1.1 Initialization 2. length 2.1 capacity 3. ensureCapacity 3.1 setLength 4. GUI 1// Fig. 10.13: StringBufferCapLen.java 2// This program demonstrates the length and 3// capacity methods of the StringBuffer class. 4import javax.swing.*; 5 6public class StringBufferCapLen { 7 public static void main( String args[] ) 8 { 9 StringBuffer buf = 10 new StringBuffer( "Hello, how are you?" ); 11 12 String output = "buf = " + buf.toString() + 13 "\nlength = " + buf.length() + 14 "\ncapacity = " + buf.capacity(); 15 16 buf.ensureCapacity( 75 ); 17 output += "\n\nNew capacity = " + buf.capacity(); 18 19 buf.setLength( 10 ); 20 output += "\n\nNew length = " + buf.length() + 21 "\nbuf = " + buf.toString(); 22 23 JOptionPane.showMessageDialog( null, output, 24 "StringBuffer length and capacity Methods", 25 JOptionPane.INFORMATION_MESSAGE ); 26 27 28 System.exit( 0 ); 29 } 30}

48 Program Output

49 10.16 StringBuffer Methods charAt, setCharAt, getChars and reverse StringBuffer methods –charAt( index ) - returns character at position index –setCharAt( index, char ) Sets character at position index to char –getChars( start, end, charArray, loc ) Copies from position start up to (not including) end into location loc in charArray –reverse - reverses contents of StringBuffer

50 Class StringBufferChars 1. main 1.1 Initialization 2. charAt 3. getChars 4. setCharAt 5. reverse 1// Fig. 10.14: StringBufferChars.java 2// The charAt, setCharAt, getChars, and reverse methods 3// of class StringBuffer. 4import javax.swing.*; 5 6public class StringBufferChars { 7 public static void main( String args[] ) 8 { 9 StringBuffer buf = new StringBuffer( "hello there" ); 10 11 String output = "buf = " + buf.toString() + 12 "\nCharacter at 0: " + buf.charAt( 0 ) + 13 "\nCharacter at 4: " + buf.charAt( 4 ); 14 15 char charArray[] = new char[ buf.length() ]; 16 buf.getChars( 0, buf.length(), charArray, 0 ); 17 output += "\n\nThe characters are: "; 18 19 for ( int i = 0; i < charArray.length; ++i ) 20 output += charArray[ i ]; 21 22 buf.setCharAt( 0, 'H' ); 23 buf.setCharAt( 6, 'T' ); 24 output += "\n\nbuf = " + buf.toString(); 25 26 buf.reverse(); 27 output += "\n\nbuf = " + buf.toString(); 28

51 6. GUI Program Output 34 System.exit( 0 ); 35 } 36} 29 JOptionPane.showMessageDialog( null, output,30 "Demonstrating StringBuffer Character Methods", 31 JOptionPane.INFORMATION_MESSAGE ); 32 33

52 10.17 StringBuffer append Methods 10 overloaded append methods –Versions for each of the primitive data types, character arrays, String s, and Object s (using toString ) –StringBuffers and append used by compiler to concatenate String s String s = "BC" + 22; actually performed as new StringBuffer( "BC").append(22).toString(); StringBuffer created with String "BC" as contents Integer 22 appended to StringBuffer StringBuffer converted to a String ( toString ) Result assigned to s

53 Class StringBufferAppend 1. main 1.1 Initialization 2. append 1// Fig. 10.15: StringBufferAppend.java 2// This program demonstrates the append 3// methods of the StringBuffer class. 4import javax.swing.*; 5 6public class StringBufferAppend { 7 public static void main( String args[] ) 8 { 9 Object o = "hello"; 10 String s = "good bye"; 11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 12 boolean b = true; 13 char c = 'Z'; 14 int i = 7; 15 long l = 10000000; 16 float f = 2.5f; 17 double d = 33.333; 18 StringBuffer buf = new StringBuffer(); 19 20 buf.append( o ); 21 buf.append( " " ); 22 23 buf.append( s ); 24 buf.append( " " ); 25 buf.append( charArray ); 26 buf.append( " " ); 27 buf.append( charArray, 0, 3 ); 28 buf.append( " " ); 29 buf.append( b ); 30 buf.append( " " );

54 2. append 3. GUI Program Output 31 buf.append( c ); 32 buf.append( " " ); 33 buf.append( i ); 34 buf.append( " " ); 35 buf.append( l ); 36 buf.append( " " ); 37 buf.append( f ); 38 buf.append( " " ); 39 buf.append( d ); 40 41 JOptionPane.showMessageDialog( null, 42 "buf = " + buf.toString(), 43 "Demonstrating StringBuffer append Methods", 44 JOptionPane.INFORMATION_MESSAGE ); 45 46 System.exit( 0 ); 47 } 48}

55 10.18 StringBuffer Insertion and Deletion Methods Nine overloaded insert methods –Insert various data at any position in StringBuffer –insert( index, data ) Inserts data right before position index index must be greater than or equal to 0 delete methods –delete( start, end ) Deletes from start up to (not including) end –deleteCharAt( index ) Deletes character at index

56 Class StringBufferInsert 1. main 1.1 Initialization 2. insert 1// Fig. 10.16: StringBufferInsert.java 2// This program demonstrates the insert and delete 3// methods of class StringBuffer. 4import javax.swing.*; 5 6public class StringBufferInsert { 7 public static void main( String args[] ) 8 { 9 Object o = "hello"; 10 String s = "good bye"; 11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 12 boolean b = true; 13 char c = 'K'; 14 int i = 7; 15 long l = 10000000; 16 float f = 2.5f; 17 double d = 33.333; 18 StringBuffer buf = new StringBuffer(); 19 20 buf.insert( 0, o ); 21 buf.insert( 0, " " ); 22 buf.insert( 0, s ); 23 buf.insert( 0, " " ); 24 buf.insert( 0, charArray ); 25 buf.insert( 0, " " ); 26 buf.insert( 0, b ); 27 28 buf.insert( 0, " " ); 29 buf.insert( 0, c ); 30 buf.insert( 0, " " );

57 2. insert 3. deleteCharAt 4. delete 31 buf.insert( 0, i ); 32 buf.insert( 0, " " ); 33 buf.insert( 0, l ); 34 buf.insert( 0, " " ); 35 buf.insert( 0, f ); 36 buf.insert( 0, " " ); 37 buf.insert( 0, d ); 38 39 String output = "buf after inserts:\n" + buf.toString(); 40 41 buf.deleteCharAt( 10 ); // delete 5 in 2.5 42 buf.delete( 2, 6 ); // delete.333 in 33.333 43 44 output += "\n\nbuf after deletes:\n" + buf.toString(); 45 46 JOptionPane.showMessageDialog( null, output, 47 "Demonstrating StringBufferer Inserts and Deletes", 48 JOptionPane.INFORMATION_MESSAGE ); 49 50 System.exit( 0 ); 51 } 52}

58 Program Output

59 10.19 Character Class Examples Classes to treat primitive variables as objects –type wrappers: Boolean, Character, Double, Float, Byte, Short, Integer and Long All but Boolean and Character derive from Number Objects of these classes can be used anywhere an Object or Number is expected –In this section, study class Character (for information on all type-wrappers see java.lang package in API) Class Character

60 10.19 Character Class Examples Class Character static methods –Let c be a char –Character.isDefined( c ) Returns true if character defined in Unicode character set –Character.isJavaIdentifierStart ( c ) Returns true if character can be used as first letter of an identifier (letter, underscore ( _ ) or dollar sign ( $ ) ) –Character.isJavaIdentifierPart( c ) Returns true if character can be used in an identifier (letter, digit, underscore, or dollar sign) –Character.isDigit( c ) –Character.isLetter( c ) Character.isLetterOrDigit( c )

61 10.19 Character Class Examples Class Character static methods –Character.isLowerCase( c ) Character.toLowerCase( c ) –Returns converted character –Returns original if no change needed –Character.isUpperCase( c ) Character.toUpperCase( c ) –Character.digit( c, radix ) Converts character c into a digit of base radix –Character.forDigit( digit, radix ) Converts integer digit into a character using base radix

62 10.19 Character Class Examples Non- static methods of class Character –c1.charValue() Returns char value stored in Character object c1 –c1.toString() Returns String representation of c1 –c1.hashCode() Performs hashCode calculations Remember, used to store objects in hash tables for fast lookup –c1.equals( c2 ) Determines if c1 has same contents as c2

63 Class StaticCharMethods 1. main 1.1 Declarations 2. Constructor 2.1 GUI 1// Fig. 10.17: StaticCharMethods.java 2// Demonstrates the static character testing methods 3// and case conversion methods of class Character 4// from the java.lang package. 5import javax.swing.*; 6import java.awt.*; 7import java.awt.event.*; 8 9public class StaticCharMethods extends JFrame { 10 private char c; 11 private JLabel prompt; 12 private JTextField input; 13 private JTextArea outputArea; 14 15 public StaticCharMethods() 16 { 17 super( "Static Character Methods" ); 18 19 Container container = getContentPane(); 20 container.setLayout( new FlowLayout() ); 21 22 prompt = 23 new JLabel( "Enter a character and press Enter" ); 24 container.add( prompt ); 25 26 input = new JTextField( 5 ); 27 input.addActionListener( 28 new ActionListener() { 29 public void actionPerformed( ActionEvent e )

64 2.2 Event handler 2.3 GUI 3. buildOutput 3.1 static method calls 32 c = s.charAt( 0 ); 34 } 35 } 36 ); 37 container.add( input ); 38 39 outputArea = new JTextArea( 10, 20 ); 40 container.add( outputArea ); 41 42 setSize( 300, 250 ); // set the window size 43 show(); // show the window 44 } 45 46 47 public void buildOutput() 48 { 49 outputArea.setText( 50 "is defined: " + Character.isDefined( c ) + 51 "\nis digit: " + Character.isDigit( c ) + 52 "\nis Java letter: " + 53 Character.isJavaIdentifierStart( c ) + 54 "\nis Java letter or digit: " + 55 Character.isJavaIdentifierPart( c ) + 56 "\nis letter: " + Character.isLetter( c ) + 57 "\nis letter or digit: " + 58 Character.isLetterOrDigit( c ) + 59 "\nis lower case: " + Character.isLowerCase( c ) + 30 { 31 String s = e.getActionCommand(); 33 buildOutput();

65 3.1 static method calls 4. main 64 63 } 67 StaticCharMethods application = new StaticCharMethods(); 68 69 application.addWindowListener( 70 new WindowAdapter() { 71 public void windowClosing( WindowEvent e ) 72 { 73 System.exit( 0 ); 74 } 75 } 76 ); 77 } 60 "\nis upper case: " + Character.isUpperCase( c ) + 61 "\nto upper case: " + Character.toUpperCase( c ) + 62 "\nto lower case: " + Character.toLowerCase( c ) ); 65 public static void main( String args[] ) 66 {

66 Program Output

67 10.20 Class StringTokenizer Tokenization –Breaking statements into pieces –Class StringTokenizer breaks a String into component tokens Tokens separated by delimiters, typically whitespace characters Other characters may be used Class StringTokenizer –One constructor: StringTokenizer( myString ) Initialize StringTokenizer with a String Default delimiter " \n\t\r" (space, newline, tab, carriage return) Other constructors allow you to specify delimiter

68 10.20 Class StringTokenizer Methods –countTokens() Determines number of tokens in String –nextToken() Returns next token as a String –nextToken( delimiterString ) Changes delimiter while tokenizing a String –hasMoreTokens() Determines if there are more tokens to be tokenized

69 Class TokenTest 1. Constructor 1.1 GUI 1// Fig. 10.20: TokenTest.java 2// Testing the StringTokenizer class of the java.util package 3import javax.swing.*; 4import java.util.*; 5import java.awt.*; 6import java.awt.event.*; 7 8public class TokenTest extends JFrame { 9 private JLabel prompt; 10 private JTextField input; 11 private JTextArea output; 12 13 public TokenTest() 14 { 15 super( "Testing Class StringTokenizer" ); 16 17 Container c = getContentPane(); 18 c.setLayout( new FlowLayout() ); 19 20 prompt = 21 new JLabel( "Enter a sentence and press Enter" ); 22 c.add( prompt ); 23 24 input = new JTextField( 20 ); 25 input.addActionListener( 26 new ActionListener() { 27 28

70 1.2 Event handler 1.2.1 Tokenize String 1.3 GUI 2. main 29 public void actionPerformed( ActionEvent e ) 30 { 31 String stringToTokenize = e.getActionCommand(); 32 StringTokenizer tokens = 33 new StringTokenizer( stringToTokenize ); 34 35 output.setText( "Number of elements: " + 36 tokens.countTokens() + 37 "\nThe tokens are:\n" ); 38 39 39 while ( tokens.hasMoreTokens() ) 40 output.append( tokens.nextToken() + "\n" ); 41 } 42 } 43 ); 44 c.add( input ); 45 46 output = new JTextArea( 10, 20 ); 47 output.setEditable( false ); 48 c.add( new JScrollPane( output ) ); 49 50 setSize( 275, 260 ); // set the window size 51 show(); // show the window 52 } 53 54 public static void main( String args[] ) 55 { 56 TokenTest app = new TokenTest(); 57 58 app.addWindowListener( 59 new WindowAdapter() { 60 public void windowClosing( WindowEvent e ) Notice loop to tokenize the string

71 Program Output 61 { 62 System.exit( 0 ); 63 } 64 } 65 ); 66 } 67}

72 10.21 A Card Shuffling and Dealing Simulation Create card shuffling/dealing simulation –Create class Card with variables face and suit –Create deck, an array of Card s –To shuffle cards Loop through deck array Generate random number (0-51) and swap current card with that card –To deal cards, walk through deck array After all cards are dealt, ask user to shuffle again

73 Class DeckOfCards 1. Instance variables 1.1 Constructor 1.2 Initialize arrays 1.3 Create deck array 1.4 Initialize deck 1// Fig. 10.21: DeckOfCards.java 2// Card shuffling and dealing program 3import javax.swing.*; 4import java.awt.*; 5import java.awt.event.*; 6 7public class DeckOfCards extends JFrame { 8 private Card deck[]; 9 private int currentCard; 10 private JButton dealButton, shuffleButton; 11 private JTextField displayCard; 12 private JLabel status; 13 14 public DeckOfCards() 15 { 16 super( "Card Dealing Program" ); 17 18 String faces[] = { "Ace", "Deuce", "Three", "Four", 19 "Five", "Six", "Seven", "Eight", 20 "Nine", "Ten", "Jack", "Queen", 21 "King" }; 22 String suits[] = { "Hearts", "Diamonds", 23 "Clubs", "Spades" }; 24 25 deck = new Card[ 52 ]; 26 currentCard = -1; 27 28 for ( int i = 0; i < deck.length; i++ ) 29 deck[ i ] = new Card( faces[ i % 13 ], 30 suits[ i / 13 ] );

74 2. GUI 2.1 Event handlers 3. GUI 31 32 Container c = getContentPane(); 33 c.setLayout( new FlowLayout() ); 34 35 dealButton = new JButton( "Deal card" ); 36 dealButton.addActionListener( 37 new ActionListener() { 38 public void actionPerformed( ActionEvent e ) 39 { 40 Card dealt = dealCard(); 41 42 43 if ( dealt != null ) { 44 displayCard.setText( dealt.toString() ); 45 status.setText( "Card #: " + currentCard ); 46 } 47 else { 48 displayCard.setText( 49 "NO MORE CARDS TO DEAL" ); 50 status.setText( 51 "Shuffle cards to continue" ); 52 } 53 } 54 } 55 ); 56 c.add( dealButton ); 57 58 shuffleButton = new JButton( "Shuffle cards" ); 59 shuffleButton.addActionListener( 60 new ActionListener() {

75 3.1 Event handler 4. GUI 5. shuffle 67 } 68 ); 69 c.add( shuffleButton ); 70 71 displayCard = new JTextField( 20 ); 72 displayCard.setEditable( false ); 73 c.add( displayCard ); 74 75 status = new JLabel(); 76 c.add( status ); 77 78 setSize( 275, 120 ); // set the window size 79 show(); // show the window 80 } 81 82 public void shuffle() 83 { 84 currentCard = -1; 85 86 for ( int i = 0; i < deck.length; i++ ) { 87 87 int j = ( int ) ( Math.random() * 52 ); 88 Card temp = deck[ i ]; // swap 89 deck[ i ] = deck[ j ]; // the 90 deck[ j ] = temp; // cards 66 } 61 public void actionPerformed( ActionEvent e ) 62 { 63 displayCard.setText( "SHUFFLING..." ); 64 shuffle(); 65 displayCard.setText( "DECK IS SHUFFLED" ); Swap current Card with random Card.

76 6. dealCard 7. main 91 } 92 93 dealButton.setEnabled( true ); 94 } 95 96 97 public Card dealCard() 98 { 99 if ( ++currentCard < deck.length ) 100 return deck[ currentCard ]; 101 else { 102 dealButton.setEnabled( false ); 103 return null; 104 } 105 } 106 107 public static void main( String args[] ) 108 { 109 DeckOfCards app = new DeckOfCards(); 110 111 app.addWindowListener( 112 new WindowAdapter() { 113 public void windowClosing( WindowEvent e ) 114 { 115 System.exit( 0 ); 116 } 117 } 118 ); 119 } 120}

77 Class Card Program Output 121 122class Card { 123 private String face; 124 private String suit; 125 126 public Card( String f, String s ) 127 { 128 face = f; 129 suit = s; 130 } 131 132 public String toString() { return face + " of " + suit; } 133}


Download ppt "Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class."

Similar presentations


Ads by Google