0% found this document useful (0 votes)
9 views

Java Characters

character in java

Uploaded by

Joel Hubahib
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Characters

character in java

Uploaded by

Joel Hubahib
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

Chapter 11 – Strings and Characters

Outline
11.1 Introduction
11.2 Fundamentals of Characters and Strings
11.3 Class String
11.3.1 String Constructors
11.3.2 String Methods length, charAt and getChars
11.3.3 Comparing Strings
11.3.4 Locating Characters and Substrings in Strings
11.3.5 Extracting Substrings from Strings
11.3.6 Concatenating Strings
11.3.7 Miscellaneous String Methods
11.3.8 String Method valueOf
11.4 Class StringBuffer
11.4.1 StringBuffer Constructors
11.4.2 StringBuffer Methods length, capacity,
setLength and ensureCapacity
11.4.3 StringBuffer Methods charAt, setCharAt,
getChars and reverse
11.4.4 StringBuffer append Methods
11.4.5 StringBuffer Insertion and Deletion Methods
1.6 Class StringTokenizer

 2003 Prentice Hall, Inc. All rights reserved.


11.1 Introduction

• String and character processing


– Class java.lang.String
– Class java.lang.StringBuffer
– Class java.util.StringTokenizer

 2003 Prentice Hall, Inc. All rights reserved.


11.2 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

 2003 Prentice Hall, Inc. All rights reserved.


11.3.1 String Constructors

• Class String
– Provides nine constructors

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.1: StringConstructors.java Outline
2 // String class constructors.
3 import javax.swing.*;
4 String defaultStringConstruct
constructor
5 public class StringConstructors {
6
ors.java
instantiates empty string
7 public static void main( String args[] )
8 { Constructor LineString
copies 17
9 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
10 byte byteArray[] = { ( byte ) 'n', ( byte ) 'e',
Constructor Linecharacter
copies 18 array
11 ( byte ) 'w', ( byte ) ' ', ( byte ) 'y',
12 ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };
13 Line 19
Constructor copies
14 String s = new String( "hello" );
character-array subset
15 Line 20
16 // use String constructors
17 String s1 = new String();
18 String s2 = new String( s );
Line
Constructor copies 21array
byte
19 String s3 = new String( charArray );
20 String s4 = new String( charArray, 6, 3 ); Line 22
21 String s5 = new String( byteArray, 4, 4 );
Constructor copies byte-array subset
22 String s6 = new String( byteArray );

 2003 Prentice Hall, Inc.


All rights reserved.
23 Outline
24 // append Strings to output
25 String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +
26 "\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6; StringConstruct
27
28 JOptionPane.showMessageDialog( null, output,
ors.java
29 "String Class Constructors", JOptionPane.INFORMATION_MESSAGE );
30
31 System.exit( 0 );
32 }
33
34 } // end class StringConstructors

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.2 String Methods length, charAt
and getChars
• Method length
– Determine String length
• Like arrays, Strings always “know” their size
• Unlike array, Strings do not have length instance variable
• Method charAt
– Get character at specific location in String
• Method getChars
– Get entire set of characters in String

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.2: StringMiscellaneous.java Outline
2 // This program demonstrates the length, charAt and getChars
3 // methods of the String class.
4 import javax.swing.*; StringMiscellan
5
6 public class StringMiscellaneous {
eous.java
7
8 public static void main( String args[] ) Line 16
9 {
10 String s1 = "hello there";
Line 21
11 char charArray[] = new char[ 5 ];
12
13 String output = "s1: " + s1;
14
15 // test length method
Determine number of
16 output += "\nLength of s1: " + s1.length();
17
characters in String s1
18 // loop through characters in s1 and display reversed
19 output += "\nThe string reversed is: ";
20 Append s1’s characters
21 for ( int count = s1.length() - 1; count >= 0; count-- )
in reverse order to
22 output += s1.charAt( count ) + " ";
String output

 2003 Prentice Hall, Inc.


All rights reserved.
23 Outline
24 // copy characters from string into charArray
Copy (some of) s1’s
25 s1.getChars( 0, 5, charArray, 0 );
26 output += "\nThe character array is: ";
characters to charArray
StringMiscellan
27
28 for ( int count = 0; count < charArray.length; count++ )
eous.java
29 output += charArray[ count ];
30 Line 25
31 JOptionPane.showMessageDialog( null, output,
32 "String class character manipulation methods",
33 JOptionPane.INFORMATION_MESSAGE );
34
35 System.exit( 0 );
36 }
37
38 } // end class StringMiscellaneous

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.3 Comparing Strings

• Comparing String objects


– Method equals
– Method equalsIgnoreCase
– Method compareTo
– Method regionMatches

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.3: StringCompare.java Outline
2 // String methods equals, equalsIgnoreCase, compareTo and regionMatches.
3 import javax.swing.JOptionPane;
4 StringCompare.j
5 public class StringCompare {
6
ava
7 public static void main( String args[] )
8 { Line 18
9 String s1 = new String( "hello" ); // s1 is a copy of "hello"
10 String s2 = "goodbye";
Line 24
11 String s3 = "Happy Birthday";
12 String s4 = "happy birthday";
13
14 String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +
15 "\ns4 = " + s4 + "\n\n";
16
Method equals tests two
17 // test for equality
18 if ( s1.equals( "hello" ) ) // true
objects for equality using
19 output += "s1 equals \"hello\"\n"; lexicographical comparison
20 else
21 output += "s1 does not equal \"hello\"\n";
22
Equality operator (==) tests
23 // test for equality with ==
24
if both references refer to
if ( s1 == "hello" ) // false; they are not the same object
25 output += "s1 equals \"hello\"\n"; same object in memory
26 else
27 output += "s1 does not equal \"hello\"\n";

 2003 Prentice Hall, Inc.


All rights reserved.
28 Outline
29 // test for equality (ignore case) Test two objects for
30 if ( s3.equalsIgnoreCase( s4 ) ) // true equality, but ignore case
31 output += "s3 equals s4\n"; StringCompare.j
of letters in Strings
32 else
33 output += "s3 does not equal s4\n";
ava
34
35 // test compareTo Line 30
Method compareTo
36 output += "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) +
37 "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) + compares String objects
Lines 36-40
38 "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) +
39 "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) +
40 "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) + "\n\n"; Line 43 and 49
41
42 // test regionMatches (case sensitive) Method regionMatches
43 if ( s3.regionMatches( 0, s4, 0, 5 ) ) compares portions of two
44 output += "First 5 characters of s3 and s4 match\n"; String objects for equality
45 else
46 output += "First 5 characters of s3 and s4 do not match\n";
47
48 // test regionMatches (ignore case)
49 if ( s3.regionMatches( true, 0, s4, 0, 5 ) )
50 output += "First 5 characters of s3 and s4 match";
51 else
52 output += "First 5 characters of s3 and s4 do not match";

 2003 Prentice Hall, Inc.


All rights reserved.
53 Outline
54 JOptionPane.showMessageDialog( null, output,
55 "String comparisons", JOptionPane.INFORMATION_MESSAGE );
56 StringCompare.j
57 System.exit( 0 );
58 }
ava
59
60 } // end class StringCompare

 2003 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 11.4: StringStartEnd.java Outline
2 // String methods startsWith and endsWith.
3 import javax.swing.*;
4 StringStartEnd.
5 public class StringStartEnd {
6
java
7 public static void main( String args[] )
8 { Line 15
9 String strings[] = { "started", "starting", "ended", "ending" };
10 String output = "";
Line 24
11
12 // test method startsWith
13 for ( int count = 0; count < strings.length; count++ )
14
15 if ( strings[ count ].startsWith( "st" ) )
16 output += "\"" + strings[ count ] + "\" starts with \"st\"\n";
17
18 output += "\n"; Method startsWith
19
determines if String starts
20 // test method startsWith starting from position
21 // 2 of the string with specified characters
22 for ( int count = 0; count < strings.length; count++ )
23
24 if ( strings[ count ].startsWith( "art", 2 ) )
25 output += "\"" + strings[ count ] +
26 "\" starts with \"art\" at position 2\n";

 2003 Prentice Hall, Inc.


All rights reserved.
27 Outline
28 output += "\n";
29
30 // test method endsWith StringStartEnd.
31 for ( int count = 0; count < strings.length; count++ )
32
java
33 if ( strings[ count ].endsWith( "ed" ) )
34 output += "\"" + strings[ count ] + "\" ends with \"ed\"\n"; Line 33
35
36 JOptionPane.showMessageDialog( null, output,
Method endsWith
37 determines
"String Class Comparisons", JOptionPane.INFORMATION_MESSAGE );if String ends
38 with specified characters
39 System.exit( 0 );
40 }
41
42 } // end class StringStartEnd

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.4 Locating Characters and
Substrings in Strings
• Search for characters in String
– Method indexOf
– Method lastIndexOf

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.5: StringIndexMethods.java Outline
2 // String searching methods indexOf and lastIndexOf.
3 import javax.swing.*;
4 StringIndexMeth
5 public class StringIndexMethods {
6
ods.java
7 public static void main( String args[] )
8 { Lines 12-16
9 String letters = "abcdefghijklmabcdefghijklm";
10
Lines 19-26
11 // test indexOf to locate a character in a string
12 Method
String output = "'c' is located at index " + letters.indexOf( 'c' ); indexOf finds first
13 occurrence of character in String
14 output += "\n'a' is located at index " + letters.indexOf( 'a', 1 );
15
16 output += "\n'$' is located at index " + letters.indexOf( '$' );
17
18 // test lastIndexOf to find a character in a string
19 output += "\n\nLast 'c' is located at index " +
20 letters.lastIndexOf( 'c' );
21
22 output += "\nLast 'a' is located at index " + Method lastIndexOf
23 letters.lastIndexOf( 'a', 25 ); finds last occurrence of
24
character in String
25 output += "\nLast '$' is located at index " +
26 letters.lastIndexOf( '$' );
27

 2003 Prentice Hall, Inc.


All rights reserved.
28 // test indexOf to locate a substring in a string Outline
29 output += "\n\n\"def\" is located at index " +
30 letters.indexOf( "def" );
31 StringIndexMeth
32 output += "\n\"def\" is located at index " +
33 letters.indexOf( "def", 7 );
ods.java
34
35 output += "\n\"hello\" is located at index " + Lines 29-46
36 letters.indexOf( "hello" ); Methods indexOf and
37
lastIndexOf can also find
38 // test lastIndexOf to find a substring in a string
39 output += "\n\nLast \"def\" is located at index " +
occurrences of substrings
40 letters.lastIndexOf( "def" );
41
42 output += "\nLast \"def\" is located at index " +
43 letters.lastIndexOf( "def", 25 );
44
45 output += "\nLast \"hello\" is located at index " +
46 letters.lastIndexOf( "hello" );
47
48 JOptionPane.showMessageDialog( null, output,
49 "String searching methods", JOptionPane.INFORMATION_MESSAGE );
50
51 System.exit( 0 );
52 }
53
54 } // end class StringIndexMethods

 2003 Prentice Hall, Inc.


All rights reserved.
Outline

StringIndexMeth
ods.java

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.5 Extracting Substrings from
Strings
• Create Strings from other Strings
– Method substring

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.6: SubString.java Outline
2 // String class substring methods.
3 import javax.swing.*;
4 SubString.java
5 public class SubString {
6
7 public static void main( String args[] ) Line 13
8 {
9 String letters = "abcdefghijklmabcdefghijklm"; Line 16
10
11 // test substring methods Beginning at index 20,
12 String output = "Substring from index 20 to end is " + extract characters from
13 "\"" + letters.substring( 20 ) + "\"\n"; String letters
14
15 output += "Substring from index 3 up to 6 is " +
16 "\"" + letters.substring( 3, 6 ) + "\""; Extract characters from index 3
17 to 6 from String letters
18 JOptionPane.showMessageDialog( null, output,
19 "String substring methods", JOptionPane.INFORMATION_MESSAGE );
20
21 System.exit( 0 );
22 }
23
24 } // end class SubString

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.6 Concatenating Strings

• Method concat
– Concatenate two String objects

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.7: StringConcatenation.java Outline
2 // String concat method.
3 import javax.swing.*;
4 StringConcatena
5 public class StringConcatenation {
6
tion.java
7 public static void main( String args[] )
8 { Line 14
9 String s1 = new String( "Happy " );
10 String s2 = new String( "Birthday" );
Concatenate String s2
to String s1Line 15
11
12 String output = "s1 = " + s1 + "\ns2 = " + s2;
13
14 output += "\n\nResult of s1.concat( s2 ) = " + s1.concat( s2 );
15 output += "\ns1 after concatenation = " + s1;
16
However, String s1 is not
17 JOptionPane.showMessageDialog( null, output, modified by method concat
18 "String method concat", JOptionPane.INFORMATION_MESSAGE );
19
20 System.exit( 0 );
21 }
22
23 } // end class StringConcatenation

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.7 Miscellaneous String Methods

• Miscellaneous String methods


– Return modified copies of String
– Return character array

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.8: StringMiscellaneous2.java Outline
2 // String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
3 import javax.swing.*;
4 StringMiscellan
5 public class StringMiscellaneous2 {
6
eous2.java
7 public static void main( String args[] )
8 { Line 17
Use method replace to return s1
9 String s1 = new String( "hello" );
10 String s2 = new String( "GOODBYE" ); copy in which every occurrence of
Line 20
11 String s3 = new String( " spaces " ); ‘l’ is replaced with ‘L’
12
13 String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = "Use method
+ s3; Line 21 to
toUpperCase
14 return s1 copy in which every
15 // test method replace Line 24
character is uppercase
16 output += "\n\nReplace 'l' with 'L' in s1: " +
17 s1.replace( 'l', 'L' );
18
Use method toLowerCase to
19 // test toLowerCase and toUpperCase return s2 copy in which every
20 output += "\n\ns1.toUpperCase() = " + s1.toUpperCase() + character is uppercase
21 "\ns2.toLowerCase() = " + s2.toLowerCase();
22 Use method trim to
23 // test trim method return s3 copy in which
24 output += "\n\ns3 after trim = \"" + s3.trim() + "\"";
whitespace is eliminated
25

 2003 Prentice Hall, Inc.


All rights reserved.
26 // test toCharArray method
Use method toCharArray to Outline
27 char charArray[] = s1.toCharArray();
28 output += "\n\ns1 as a character array = ";
return character array of s1
29 StringMiscellan
30 for ( int count = 0; count < charArray.length; ++count )
31 output += charArray[ count ];
eous2.java
32
33 JOptionPane.showMessageDialog( null, output, Line 27
34 "Additional String methods", JOptionPane.INFORMATION_MESSAGE );
35
36 System.exit( 0 );
37 }
38
39 } // end class StringMiscellaneous2

 2003 Prentice Hall, Inc.


All rights reserved.
11.3.8 String Method valueOf

• String provides static class methods


– Method valueOf
• Returns String representation of object, data, etc.

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.9: StringValueOf.java Outline
2 // String valueOf methods.
3 import javax.swing.*;
4 StringValueOf.j
5 public class StringValueOf {
6
ava
7 public static void main( String args[] )
8 { Lines 20-26
9 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
10 boolean booleanValue = true;
11 char characterValue = 'Z';
12 int integerValue = 7;
13 long longValue = 10000000L;
14 float floatValue = 2.5f; // f suffix indicates that 2.5 is a float
15 double doubleValue = 33.333;
16 Object objectRef = "hello"; // assign string to an Object reference
17
18 String output = "char array = " + String.valueOf( charArray ) +
19 "\npart of char array = " + String.valueOf( charArray, 3, 3 ) +
20 "\nboolean = " + String.valueOf( booleanValue ) +
21 "\nchar = " + String.valueOf( characterValue ) +
22 "\nint = " + String.valueOf( integerValue ) + static method valueOf of
23 "\nlong = " + String.valueOf( longValue ) + class String returns String
24 "\nfloat = " + String.valueOf( floatValue ) + representation of various types
25 "\ndouble = " + String.valueOf( doubleValue ) +
26 "\nObject = " + String.valueOf( objectRef );

 2003 Prentice Hall, Inc.


All rights reserved.
27 Outline
28 JOptionPane.showMessageDialog( null, output,
29 "String valueOf methods", JOptionPane.INFORMATION_MESSAGE );
30 StringValueOf.j
31 System.exit( 0 );
32 }
ava
33
34 } // end class StringValueOf

 2003 Prentice Hall, Inc.


All rights reserved.
11.4 Class StringBuffer

• Class StringBuffer
– When String object is created, its contents cannot change
– Used for creating and manipulating dynamic string data
• i.e., modifiable Strings
– Can store characters based on capacity
• Capacity expands dynamically to handle additional characters
– Uses operators + and += for String concatenation

 2003 Prentice Hall, Inc. All rights reserved.


11.4.1 StringBuffer Constructors

• Three StringBuffer constructors


– Default creates StringBuffer with no characters
• Capacity of 16 characters

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.10: StringBufferConstructors.java Outline
2 // StringBuffer constructors. Default constructor creates
3 import javax.swing.*; empty StringBuffer with
4
capacity of StringBufferCon
16 characters
5 public class StringBufferConstructors {
6
structors.java
7 public static void main( String args[] )
Second constructor creates empty
8 { Line 9
9 StringBuffer buffer1 = new StringBuffer();
StringBuffer with capacity of
10 StringBuffer buffer2 = new StringBuffer( 10 ); specified (10) characters
Line 10
11 StringBuffer buffer3 = new StringBuffer( "hello" );
12 Third constructor creates
13 String output = "buffer1 = \"" + buffer1.toString() + "\"" + Line 11
StringBuffer with
14 "\nbuffer2 = \"" + buffer2.toString() + "\"" +
String “hello” and
15 "\nbuffer3 = \"" + buffer3.toString() + "\""; Lines 13-15
16 capacity of 16 characters
17 JOptionPane.showMessageDialog( null, output,
18 "StringBuffer constructors", JOptionPane.INFORMATION_MESSAGE );
MethodtoString returns
19
String representation of
20 System.exit( 0 );
21 } StringBuffer
22
23 } // end class StringBufferConstructors

 2003 Prentice Hall, Inc.


All rights reserved.
11.4.2 StringBuffer Methods length,
capacity, setLength and ensureCapacity

• Method length
– Return StringBuffer length
• Method capacity
– Return StringBuffer capacity
• Method setLength
– Increase or decrease StringBuffer length
• Method ensureCapacity
– Set StringBuffer capacity
– Guarantee that StringBuffer has minimum capacity

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.11: StringBufferCapLen.java Outline
2 // StringBuffer length, setLength, capacity and ensureCapacity methods.
3 import javax.swing.*;
4 StringBufferCap
5 public class StringBufferCapLen {
6
Len.java
7 public static void main( String args[] )
8 { Method length
Line 12 returns
9 StringBuffer buffer = new StringBuffer( "Hello, how are you?" ); StringBuffer length
10
Line 12
11 String output = "buffer = " + buffer.toString() + "\nlength = " +
Method capacity returns
12 buffer.length() + "\ncapacity = " + buffer.capacity();
13 StringBuffer
Line 14 capacity
14 buffer.ensureCapacity( 75 );
15 output += "\n\nNew capacity = " + buffer.capacity(); Line 17
Use method ensureCapacity
16
17 buffer.setLength( 10 );
to set capacity to 75
18 output += "\n\nNew length = " + buffer.length() +
19 "\nbuf = " + buffer.toString(); Use method setLength
20 to set length to 10
21 JOptionPane.showMessageDialog( null, output,
22 "StringBuffer length and capacity Methods",
23 JOptionPane.INFORMATION_MESSAGE );
24

 2003 Prentice Hall, Inc.


All rights reserved.
25 System.exit( 0 ); Outline
26 }
27
28 } // end class StringBufferCapLen StringBufferCap
Len.java

Only 10 characters
from
StringBuffer are
printed

Only 10 characters from


StringBuffer are printed

 2003 Prentice Hall, Inc.


All rights reserved.
11.4.3 StringBuffer Methods charAt,
setCharAt, getChars and reverse
• 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

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.12: StringBufferChars.java Outline
2 // StringBuffer methods charAt, setCharAt, getChars and reverse.
3 import javax.swing.*;
4 StringBufferCha
5 public class StringBufferChars {
6
rs.java
7 public static void main( String args[] )
8 { Lines 12-13
Return StringBuffer
9 StringBuffer buffer = new StringBuffer( "hello there" );
10 characters at indices 0
Line 16
11 String output = "buffer = " + buffer.toString() + and 4, respectively
12 "\nCharacter at 0: " + buffer.charAt( 0 ) +
13 "\nCharacter at 4: " + buffer.charAt( 4 ); Lines 22-23
14
15 char charArray[] = new char[ buffer.length() ]; Return character array
16 buffer.getChars( 0, buffer.length(), charArray, 0 );
from StringBuffer
17 output += "\n\nThe characters are: ";
18
19 for ( int count = 0; count < charArray.length; ++count )
20 output += charArray[ count ];
21
22 buffer.setCharAt( 0, 'H' ); Replace characters at
23 buffer.setCharAt( 6, 'T' ); indices 0 and 6 with ‘H’
24 output += "\n\nbuf = " + buffer.toString(); and ‘T,’ respectively
25

 2003 Prentice Hall, Inc.


All rights reserved.
26 buffer.reverse(); Outline
27 output += "\n\nbuf = " + buffer.toString();
Reverse characters in
28
29 JOptionPane.showMessageDialog( null, output,
StringBuffer
StringBufferCha
30 "StringBuffer character methods",
31 JOptionPane.INFORMATION_MESSAGE );
rs.java
32
33 System.exit( 0 ); Lines 26
34 }
35
36 } // end class StringBufferChars

 2003 Prentice Hall, Inc.


All rights reserved.
11.4.4 StringBuffer append Methods

• Method append
– Allow data values to be added to StringBuffer

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.13: StringBufferAppend.java Outline
2 // StringBuffer append methods.
3 import javax.swing.*;
4 StringBufferApp
5 public class StringBufferAppend {
6
end.java
7 public static void main( String args[] )
8 { Line 21
9 Object objectRef = "hello";
10 String string = "goodbye";
Line 23
11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
12 boolean booleanValue = true;
13 char characterValue = 'Z'; Line 25
14 int integerValue = 7;
15 long longValue = 10000000; Line 27
16 float floatValue = 2.5f; // f suffix indicates 2.5 is a float
17 double doubleValue = 33.333;
18 StringBuffer lastBuffer = new StringBuffer( "last StringBuffer" );
19 StringBuffer buffer = new StringBuffer();
20 Append String “hello”
21 buffer.append( objectRef );
to StringBuffer
22 buffer.append( " " ); // each of these contains two spaces
23 buffer.append( string );
24 buffer.append( " " ); Append String “goodbye”
25 buffer.append( charArray );
26 buffer.append( " " );
Append “a b c d e f”
27 buffer.append( charArray, 0, 3 );
Append “a b c”

 2003 Prentice Hall, Inc.


All rights reserved.
28 buffer.append( " " ); Outline
29 buffer.append( booleanValue );
30 buffer.append( " " );
31 buffer.append( characterValue ); StringBufferApp
32 buffer.append( " " );
Append boolean, char, int,
end.java
33 buffer.append( integerValue );
34 buffer.append( " " ); long, float and double
35 buffer.append( longValue ); Line 29-39
36 buffer.append( " " );
37 buffer.append( floatValue );
38 buffer.append( " " );
39 buffer.append( doubleValue );
40 buffer.append( " " );
41 buffer.append( lastBuffer );
42
43 JOptionPane.showMessageDialog( null,
44 "buffer = " + buffer.toString(), "StringBuffer append Methods",
45 JOptionPane.INFORMATION_MESSAGE );
46
47 System.exit( 0 );
48 }
49
50 } // end StringBufferAppend

 2003 Prentice Hall, Inc.


All rights reserved.
11.4.5 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

 2003 Prentice Hall, Inc. All rights reserved.


1 // Fig. 11.14: StringBufferInsert.java Outline
2 // StringBuffer methods insert and delete.
3 import javax.swing.*;
4 StringBufferIns
5 public class StringBufferInsert {
6
ert.java
7 public static void main( String args[] )
8 { Lines 20-26
9 Object objectRef = "hello";
10 String string = "goodbye";
11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
12 boolean booleanValue = true;
13 char characterValue = 'K';
14 int integerValue = 7;
15 long longValue = 10000000;
16 float floatValue = 2.5f; // f suffix indicates that 2.5 is a float
17 double doubleValue = 33.333;
18 StringBuffer buffer = new StringBuffer();
19
20 buffer.insert( 0, objectRef );
21 buffer.insert( 0, " " ); // each of these contains two spaces
22 buffer.insert( 0, string );
23 buffer.insert( 0, " " );
24 buffer.insert( 0, charArray );
Use method insert to insert
25 buffer.insert( 0, " " ); data in beginning of
26 buffer.insert( 0, charArray, 3, 3 ); StringBuffer

 2003 Prentice Hall, Inc.


All rights reserved.
27 buffer.insert( 0, " " ); Outline
28 buffer.insert( 0, booleanValue );
29 buffer.insert( 0, " " );
30 buffer.insert( 0, characterValue );
31 buffer.insert( 0, " " ); Use method insert to insertStringBufferIns
32 buffer.insert( 0, integerValue ); data in beginning of ert.java
33 buffer.insert( 0, " " ); StringBuffer
34 buffer.insert( 0, longValue ); Lines 27-38
35 buffer.insert( 0, " " );
36 buffer.insert( 0, floatValue );
Line 42
37 buffer.insert( 0, " " );
38 buffer.insert( 0, doubleValue ); Use method deleteCharAt to
39 Lineindex
remove character from 43 10 in
40 String output = "buffer after inserts:\n" + buffer.toString(); StringBuffer
41
42 buffer.deleteCharAt( 10 ); // delete 5 in 2.5
43 buffer.delete( 2, 6 ); // delete .333 in 33.333
44 Remove characters from
45 output += "\n\nbuffer after deletes:\n" + buffer.toString(); indices 2 through 5 (inclusive)
46
47 JOptionPane.showMessageDialog( null, output,
48 "StringBuffer insert/delete", JOptionPane.INFORMATION_MESSAGE );
49
50 System.exit( 0 );
51 }
52
53 } // end class StringBufferInsert

 2003 Prentice Hall, Inc.


All rights reserved.
Outline

StringBufferIns
ert.java

 2003 Prentice Hall, Inc.


All rights reserved.
11.6 Class StringTokenizer

• Tokenizer
– Partition String into individual substrings
– Use delimiter
– Java offers java.util.StringTokenizer

 2003 Prentice Hall, Inc. All rights reserved.

You might also like