0% found this document useful (0 votes)
77 views46 pages

Strings and Characters: String String

The document discusses classes and methods for working with strings in Java, including the String, StringBuffer, and StringTokenizer classes. It covers String constructors, methods for getting string length, characters, and substrings. Methods are presented for comparing strings, locating characters and substrings within strings, and extracting substrings. The StringBuffer class supports mutable string operations.

Uploaded by

Nitish Sarin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views46 pages

Strings and Characters: String String

The document discusses classes and methods for working with strings in Java, including the String, StringBuffer, and StringTokenizer classes. It covers String constructors, methods for getting string length, characters, and substrings. Methods are presented for comparing strings, locating characters and substrings within strings, and extracting substrings. The StringBuffer class supports mutable string operations.

Uploaded by

Nitish Sarin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

Strings and Characters

Outline
11.1
11.2
11.3

11.4

1.6

Introduction
Fundamentals of Characters and Strings
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
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
Class StringTokenizer

11.1 Introduction
String and character processing
Class java.lang.String
Class java.lang.StringBuffer
Class java.util.StringTokenizer

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

11.3.1 String Constructors


Class String
Provides nine constructors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Outline

// Fig. 11.1: StringConstructors.java


// String class constructors.
import javax.swing.*;
public class StringConstructors {

String defaultStringConstruct
constructor
ors.java
instantiates empty
string

public static void main( String args[] )


{
Constructor
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
byte byteArray[] = { ( byte ) 'n', ( byte ) 'e',
Constructor
( byte ) 'w', ( byte ) ' ', ( byte ) 'y',
( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };
String s = new String( "hello" );
// use
String
String
String
String
String
String

String constructors
s1 = new String();
s2 = new String( s );
s3 = new String( charArray );
s4 = new String( charArray, 6, 3 );
s5 = new String( byteArray, 4, 4 );
s6 = new String( byteArray );

LineString
17
copies
Linecharacter
18
copies
array

Line 19
Constructor copies
character-array subset
Line 20

Line
21array
Constructor copies
byte
Line 22
Constructor copies byte-array subset

23
24
25
26
27
28
29
30
31
32
33
34

// append Strings to output


String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +
"\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6;
JOptionPane.showMessageDialog( null, output,
"String Class Constructors", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringConstructors

Outline
StringConstruct
ors.java

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

// Fig. 11.2: StringMiscellaneous.java


// This program demonstrates the length, charAt and getChars
// methods of the String class.
import javax.swing.*;
public class StringMiscellaneous {
public static void main( String args[] )
{
String s1 = "hello there";
char charArray[] = new char[ 5 ];

Outline
StringMiscellan
eous.java
Line 16
Line 21

String output = "s1: " + s1;


// test length method
output += "\nLength of s1: " + s1.length();

Determine number of
characters in String s1

// loop through characters in s1 and display reversed


output += "\nThe string reversed is: ";
for ( int count = s1.length() - 1; count >= 0; count-- )
output += s1.charAt( count ) + " ";

Append s1s characters


in reverse order to
String output

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

// copy characters from string into charArray


s1.getChars( 0, 5, charArray, 0 );
output += "\nThe character array is: ";
for ( int count = 0; count < charArray.length;
output += charArray[ count ];

Copy (some of) s1s


characters to charArray
StringMiscellan
eous.java
count++ )

JOptionPane.showMessageDialog( null, output,


"String class character manipulation methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringMiscellaneous

Outline

Line 25

11.3.3 Comparing Strings


Comparing String objects

Method equals
Method equalsIgnoreCase
Method compareTo
Method regionMatches

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// Fig. 11.3: StringCompare.java


// String methods equals, equalsIgnoreCase, compareTo and regionMatches.
import javax.swing.JOptionPane;

Outline
StringCompare.j
ava

public class StringCompare {


public static void main( String args[] )
{
String s1 = new String( "hello" ); // s1 is a copy of "hello"
String s2 = "goodbye";
String s3 = "Happy Birthday";
String s4 = "happy birthday";

Line 18
Line 24

String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +


"\ns4 = " + s4 + "\n\n";
// test for equality
if ( s1.equals( "hello" ) ) // true
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";

Method equals tests two


objects for equality using
lexicographical comparison
Equality operator (==) tests

// test for equality with ==


if both references refer to
if ( s1 == "hello" ) // false; they are not the same object
same object in memory
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

// test for equality (ignore case)


if ( s3.equalsIgnoreCase( s4 ) ) // true
output += "s3 equals s4\n";
else
output += "s3 does not equal s4\n";
// test compareTo
output += "\ns1.compareTo( s2
"\ns2.compareTo( s1 ) is "
"\ns1.compareTo( s1 ) is "
"\ns3.compareTo( s4 ) is "
"\ns4.compareTo( s3 ) is "

)
+
+
+
+

Test two objects for


equality, but ignore case
of letters in Strings

is " + s1.compareTo( s2 ) +
s2.compareTo( s1 ) +
s1.compareTo( s1 ) +
s3.compareTo( s4 ) +
s4.compareTo( s3 ) + "\n\n";

Outline
StringCompare.j
ava
Line 30
Method compareTo
compares String objects
Lines 36-40
Line 43 and 49

Method regionMatches
// test regionMatches (case sensitive)
if ( s3.regionMatches( 0, s4, 0, 5 ) )
compares portions of two
output += "First 5 characters of s3 and s4 match\n";
String objects for equality
else
output += "First 5 characters of s3 and s4 do not match\n";
// test regionMatches (ignore case)
if ( s3.regionMatches( true, 0, s4, 0, 5 ) )
output += "First 5 characters of s3 and s4 match";
else
output += "First 5 characters of s3 and s4 do not match";

53
54
55
56
57
58
59
60

JOptionPane.showMessageDialog( null, output,


"String comparisons", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringCompare

Outline
StringCompare.j
ava

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Outline

// Fig. 11.4: StringStartEnd.java


// String methods startsWith and endsWith.
import javax.swing.*;

StringStartEnd.
java

public class StringStartEnd {


public static void main( String args[] )
{
String strings[] = { "started", "starting", "ended", "ending" };
String output = "";

Line 15
Line 24

// test method startsWith


for ( int count = 0; count < strings.length; count++ )
if ( strings[ count ].startsWith( "st" ) )
output += "\"" + strings[ count ] + "\" starts with \"st\"\n";
output += "\n";
// test method startsWith starting from position
// 2 of the string
for ( int count = 0; count < strings.length; count++ )
if ( strings[ count ].startsWith( "art", 2 ) )
output += "\"" + strings[ count ] +
"\" starts with \"art\" at position 2\n";

Method startsWith
determines if String starts
with specified characters

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

Outline

output += "\n";
// test method endsWith
for ( int count = 0; count < strings.length; count++ )

StringStartEnd.
java

if ( strings[ count ].endsWith( "ed" ) )


output += "\"" + strings[ count ] + "\" ends with \"ed\"\n";

Line 33

Method endsWith
String ends
with specified characters

JOptionPane.showMessageDialog( null, output,


determines
"String Class Comparisons", JOptionPane.INFORMATION_MESSAGE
);if
System.exit( 0 );
}
} // end class StringStartEnd

11.3.4 Locating Characters and Substrings


in Strings
Search for characters in String
Method indexOf
Method lastIndexOf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Outline

// Fig. 11.5: StringIndexMethods.java


// String searching methods indexOf and lastIndexOf.
import javax.swing.*;

StringIndexMeth
ods.java

public class StringIndexMethods {


public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";

Lines 12-16

// test indexOf to locate a character in a string


Method
String output = "'c' is located at index " + letters.indexOf( 'c'
);

Lines 19-26

indexOf finds first


occurrence of character in String

output += "\n'a' is located at index " + letters.indexOf( 'a', 1 );


output += "\n'$' is located at index " + letters.indexOf( '$' );
// test lastIndexOf to find a character in a string
output += "\n\nLast 'c' is located at index " +
letters.lastIndexOf( 'c' );
output += "\nLast 'a' is located at index " +
letters.lastIndexOf( 'a', 25 );
output += "\nLast '$' is located at index " +
letters.lastIndexOf( '$' );

Method lastIndexOf
finds last occurrence of
character in String

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

// test indexOf to locate a substring in a string


output += "\n\n\"def\" is located at index " +
letters.indexOf( "def" );
output += "\n\"def\" is located at index " +
letters.indexOf( "def", 7 );
output += "\n\"hello\" is located at index " +
letters.indexOf( "hello" );
// test lastIndexOf to find a substring in a string
output += "\n\nLast \"def\" is located at index " +
letters.lastIndexOf( "def" );
output += "\nLast \"def\" is located at index " +
letters.lastIndexOf( "def", 25 );
output += "\nLast \"hello\" is located at index " +
letters.lastIndexOf( "hello" );
JOptionPane.showMessageDialog( null, output,
"String searching methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}

// end class StringIndexMethods

Outline
StringIndexMeth
ods.java
Lines 29-46
Methods indexOf and
lastIndexOf can also find
occurrences of substrings

Outline
StringIndexMeth
ods.java

11.3.5 Extracting Substrings from Strings


Create Strings from other Strings
Method substring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 11.6: SubString.java


// String class substring methods.
import javax.swing.*;

SubString.java

public class SubString {

Line 13

public static void main( String args[] )


{
String letters = "abcdefghijklmabcdefghijklm";
// test substring methods
String output = "Substring from index 20 to end is " +
"\"" + letters.substring( 20 ) + "\"\n";
output += "Substring from index 3 up to 6 is " +
"\"" + letters.substring( 3, 6 ) + "\"";

Line 16
Beginning at index 20,
extract characters from
String letters
Extract characters from index 3
to 6 from String letters

JOptionPane.showMessageDialog( null, output,


"String substring methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class SubString

11.3.6 Concatenating Strings


Method concat
Concatenate two String objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Outline

// Fig. 11.7: StringConcatenation.java


// String concat method.
import javax.swing.*;

StringConcatena
tion.java

public class StringConcatenation {


public static void main( String args[] )
{
String s1 = new String( "Happy " );
String s2 = new String( "Birthday" );

Line 14
Concatenate String s2
Line 15
to String s1

String output = "s1 = " + s1 + "\ns2 = " + s2;


output += "\n\nResult of s1.concat( s2 ) = " + s1.concat( s2 );
output += "\ns1 after concatenation = " + s1;

However, String s1 is not


modified by method concat

JOptionPane.showMessageDialog( null, output,


"String method concat", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringConcatenation

11.3.7 Miscellaneous String Methods


Miscellaneous String methods
Return modified copies of String
Return character array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// Fig. 11.8: StringMiscellaneous2.java


// String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
import javax.swing.*;

StringMiscellan
eous2.java

public class StringMiscellaneous2 {


public static void
{
String s1 = new
String s2 = new
String s3 = new

main( String args[] )


String( "hello" );
String( "GOODBYE" );
String( "
spaces
" );

Outline

Line 17
Use method replace to return s1
copy in which every occurrence of
Line 20
l is replaced with L
Line 21 to
toUpperCase
return s1 copy in which every
Line 24
character is uppercase

String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = "Use


+ s3;
method
// test method replace
output += "\n\nReplace 'l' with 'L' in s1: " +
s1.replace( 'l', 'L' );
// test toLowerCase and toUpperCase
output += "\n\ns1.toUpperCase() = " + s1.toUpperCase()
"\ns2.toLowerCase() = " + s2.toLowerCase();
// test trim method
output += "\n\ns3 after trim = \"" + s3.trim() + "\"";

Use method toLowerCase to


return s2 copy in which every
character is uppercase
+
Use method trim to
return s3 copy in which
whitespace is eliminated

26
27
28
29
30
31
32
33
34
35
36
37
38
39

// test toCharArray method


char charArray[] = s1.toCharArray();
output += "\n\ns1 as a character array = ";

Use method toCharArray to


return character array of s1

for ( int count = 0; count < charArray.length; ++count )


output += charArray[ count ];
JOptionPane.showMessageDialog( null, output,
"Additional String methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringMiscellaneous2

Outline

StringMiscellan
eous2.java
Line 27

11.3.8 String Method valueOf


String provides static class methods
Method valueOf
Returns String representation of object, data, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

// Fig. 11.9: StringValueOf.java


// String valueOf methods.
import javax.swing.*;
public class StringValueOf {
public static void main( String args[] )
{
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'Z';
int integerValue = 7;
long longValue = 10000000L;
float floatValue = 2.5f; // f suffix indicates that 2.5 is a float
double doubleValue = 33.333;
Object objectRef = "hello"; // assign string to an Object reference

Outline
StringValueOf.j
ava
Lines 20-26

String output = "char array = " + String.valueOf( charArray ) +


"\npart of char array = " + String.valueOf( charArray, 3, 3 ) +
"\nboolean = " + String.valueOf( booleanValue ) +
"\nchar = " + String.valueOf( characterValue ) +
static method valueOf of
"\nint = " + String.valueOf( integerValue ) +
class String returns String
"\nlong = " + String.valueOf( longValue ) +
"\nfloat = " + String.valueOf( floatValue ) +
representation of various types
"\ndouble = " + String.valueOf( doubleValue ) +
"\nObject = " + String.valueOf( objectRef );

27
28
29
30
31
32
33
34

JOptionPane.showMessageDialog( null, output,


"String valueOf methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringValueOf

Outline
StringValueOf.j
ava

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

11.4.1 StringBuffer Constructors


Three StringBuffer constructors
Default creates StringBuffer with no characters
Capacity of 16 characters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Outline

// Fig. 11.10: StringBufferConstructors.java


// StringBuffer constructors.
import javax.swing.*;

Default constructor creates


empty StringBuffer with
capacity of StringBufferCon
16 characters
structors.java

public class StringBufferConstructors {


public static void main( String args[] )
{
StringBuffer buffer1 = new StringBuffer();
StringBuffer buffer2 = new StringBuffer( 10 );
StringBuffer buffer3 = new StringBuffer( "hello" );

Second constructor creates empty


Line 9
StringBuffer with capacity of
specified (10) characters
Line 10

String output = "buffer1 = \"" + buffer1.toString() + "\"" +


"\nbuffer2 = \"" + buffer2.toString() + "\"" +
"\nbuffer3 = \"" + buffer3.toString() + "\"";

Third constructor creates


Line 11
StringBuffer with
StringLines
hello
13-15 and
capacity of 16 characters

JOptionPane.showMessageDialog( null, output,


"StringBuffer constructors", JOptionPane.INFORMATION_MESSAGE );
Method
System.exit( 0 );
}
} // end class StringBufferConstructors

toString returns
String representation of
StringBuffer

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// Fig. 11.11: StringBufferCapLen.java


// StringBuffer length, setLength, capacity and ensureCapacity methods.
import javax.swing.*;

StringBufferCap
Len.java

public class StringBufferCapLen {


public static void main( String args[] )
{
StringBuffer buffer = new StringBuffer( "Hello, how are you?" );
String output = "buffer = " + buffer.toString() + "\nlength = " +
buffer.length() + "\ncapacity = " + buffer.capacity();
buffer.ensureCapacity( 75 );
output += "\n\nNew capacity = " + buffer.capacity();
buffer.setLength( 10 );
output += "\n\nNew length = " + buffer.length() +
"\nbuf = " + buffer.toString();
JOptionPane.showMessageDialog( null, output,
"StringBuffer length and capacity Methods",
JOptionPane.INFORMATION_MESSAGE );

Outline

Method length
Line 12 returns
StringBuffer length
Line 12
Method capacity returns
StringBuffer
Line 14 capacity

Line 17
Use method ensureCapacity
to set capacity to 75
Use method setLength
to set length to 10

25
26
27
28

System.exit( 0 );
}
} // end class StringBufferCapLen

Outline
StringBufferCap
Len.java
Only 10 characters
from
StringBuffer are
printed

Only 10 characters from


StringBuffer are printed

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// Fig. 11.12: StringBufferChars.java


// StringBuffer methods charAt, setCharAt, getChars and reverse.
import javax.swing.*;
public class StringBufferChars {
public static void main( String args[] )
{
StringBuffer buffer = new StringBuffer( "hello there" );
String output = "buffer = " + buffer.toString() +
"\nCharacter at 0: " + buffer.charAt( 0 ) +
"\nCharacter at 4: " + buffer.charAt( 4 );
char charArray[] = new char[ buffer.length() ];
buffer.getChars( 0, buffer.length(), charArray, 0 );
output += "\n\nThe characters are: ";

Outline
StringBufferCha
rs.java
Lines 12-13
Return StringBuffer
characters at indices 0
Line 16
and 4, respectively
Lines 22-23
Return character array
from StringBuffer

for ( int count = 0; count < charArray.length; ++count )


output += charArray[ count ];
buffer.setCharAt( 0, 'H' );
buffer.setCharAt( 6, 'T' );
output += "\n\nbuf = " + buffer.toString();

Replace characters at
indices 0 and 6 with H
and T, respectively

26
27
28
29
30
31
32
33
34
35
36

buffer.reverse();
output += "\n\nbuf = " + buffer.toString();
JOptionPane.showMessageDialog( null, output,
"StringBuffer character methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringBufferChars

Outline

Reverse characters in
StringBuffer
StringBufferCha
rs.java
Lines 26

11.4.4 StringBuffer append Methods


Method append
Allow data values to be added to StringBuffer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Outline

// Fig. 11.13: StringBufferAppend.java


// StringBuffer append methods.
import javax.swing.*;

StringBufferApp
end.java

public class StringBufferAppend {


public static void main( String args[] )
{
Object objectRef = "hello";
String string = "goodbye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'Z';
int integerValue = 7;
long longValue = 10000000;
float floatValue = 2.5f; // f suffix indicates 2.5 is a float
double doubleValue = 33.333;
StringBuffer lastBuffer = new StringBuffer( "last StringBuffer" );
StringBuffer buffer = new StringBuffer();
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(

Line 21
Line 23
Line 25
Line 27

Append String hello

objectRef );
to StringBuffer
" " );
// each of these contains two spaces
string );
Append String goodbye
" " );
charArray );
Append a b c d e f
" " );
charArray, 0, 3 );

Append a b c

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(

" " );
booleanValue );
" " );
characterValue );
" " );
integerValue );
" " );
longValue );
" " );
floatValue );
" " );
doubleValue );
" " );
lastBuffer );

Outline
StringBufferApp
Append boolean, char,
int,
end.java
long, float and double
Line 29-39

JOptionPane.showMessageDialog( null,
"buffer = " + buffer.toString(), "StringBuffer append Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end StringBufferAppend

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

// Fig. 11.14: StringBufferInsert.java


// StringBuffer methods insert and delete.
import javax.swing.*;
public class StringBufferInsert {
public static void main( String args[] )
{
Object objectRef = "hello";
String string = "goodbye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'K';
int integerValue = 7;
long longValue = 10000000;
float floatValue = 2.5f; // f suffix indicates that 2.5 is a float
double doubleValue = 33.333;
StringBuffer buffer = new StringBuffer();
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(

0,
0,
0,
0,
0,
0,
0,

objectRef );
" " ); // each of these contains two spaces
string );
" " );
Use method insert to insert
charArray );
data in beginning of
" " );
StringBuffer
charArray, 3, 3 );

Outline
StringBufferIns
ert.java
Lines 20-26

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(

0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,

Outline

" " );
booleanValue );
" " );
characterValue );
" " );
integerValue );
" " );
longValue );
" " );
floatValue );
" " );
doubleValue );

Use method insert to insertStringBufferIns


ert.java
data in beginning of
StringBuffer
Lines 27-38
Line 42

String output = "buffer after inserts:\n" +


buffer.deleteCharAt( 10 );
buffer.delete( 2, 6 );

Use method deleteCharAt to


Lineindex
43 10 in
remove character from
buffer.toString();
StringBuffer

// delete 5 in 2.5
// delete .333 in 33.333

output += "\n\nbuffer after deletes:\n" +

Remove characters from


buffer.toString(); indices 2 through 5 (inclusive)

JOptionPane.showMessageDialog( null, output,


"StringBuffer insert/delete", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringBufferInsert

Outline
StringBufferIns
ert.java

11.6 Class StringTokenizer


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

You might also like