Professional Documents
Culture Documents
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
2003 Prentice Hall, Inc. All rights reserved.
11.1 Introduction
String and character processing
Class java.lang.String
Class java.lang.StringBuffer
Class java.lang.Character
Class java.util.StringTokenizer
String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Outline
String defaultStringConstruct
constructor
instantiates empty
ors.java
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
Outline
StringConstruct
ors.java
System.exit( 0 );
}
} // end class StringConstructors
Method charAt
Get character at specific location in String
Method getChars
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Outline
StringMiscellan
eous.java
Line 16
Line 21
Determine number of
characters in String s1
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Outline
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
Outline
StringCompare.j
ava
Line 18
Line 24
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
)
+
+
+
+
Outline
is " + s1.compareTo( s2 ) +
s2.compareTo( s1 ) +
s1.compareTo( s1 ) +
s3.compareTo( s4 ) +
s4.compareTo( s3 ) + "\n\n";
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
Outline
StringCompare.j
ava
System.exit( 0 );
}
} // end class StringCompare
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
StringStartEnd.
java
Line 15
Line 24
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
Line 33
Method endsWith
String ends
with specified characters
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
StringIndexMeth
ods.java
Lines 12-16
Lines 19-26
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
Outline
StringIndexMeth
ods.java
Lines 29-46
Methods indexOf and
lastIndexOf can also find
occurrences of substrings
Outline
StringIndexMeth
ods.java
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
SubString.java
Line 13
Line 16
Beginning at index 20,
extract characters from
String letters
Extract characters from index 3
to 6 from String letters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Outline
StringConcatena
tion.java
Line 14
Concatenate String s2
Line 15
to String s1
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
Outline
StringMiscellan
eous2.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Outline
StringMiscellan
eous2.java
Line 27
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
StringValueOf.j
ava
Lines 20-26
27
28
29
30
31
32
33
34
Outline
StringValueOf.j
ava
System.exit( 0 );
}
} // end class StringValueOf
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
toString returns
String representation of
StringBuffer
Method length
Return StringBuffer length
Method capacity
Return StringBuffer capacity
Method setLength
Increase or decrease StringBuffer length
Method ensureCapacity
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
StringBufferCap
Len.java
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
Outline
System.exit( 0 );
}
} // end class StringBufferCapLen
StringBufferCap
Len.java
Only 10 characters
from
StringBuffer are
printed
Method setCharAt
Set StringBuffer character at specified index
Method getChars
Return character array from StringBuffer
Method reverse
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
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
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 );
Outline
Reverse characters in
StringBuffer
StringBufferCha
rs.java
Lines 26
System.exit( 0 );
}
} // end class StringBufferChars
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
StringBufferApp
end.java
Line 21
Line 23
Line 25
Line 27
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
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
StringBufferIns
ert.java
0,
0,
0,
0,
0,
0,
0,
Lines 20-26
objectRef );
" " ); // each of these contains two spaces
string );
" " );
Use method insert to insert
charArray );
data in beginning of
" " );
StringBuffer
charArray, 3, 3 );
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 );
// delete 5 in 2.5
// delete .333 in 33.333
Outline
StringBufferIns
ert.java
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
StaticCharMetho
ds.java
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Outline
inputField.addActionListener(
new ActionListener() {
StaticCharMetho
ds.java
} // end constructor
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Outline
Determine whether
Line
60 or digit
c is
letter
Lines
61-62c is
Determine
whether
uppercase or lowercase
Outline
StaticCharMetho
ds.java
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
Outline
StaticCharMetho
ds2.java
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
Outline
StaticCharMetho
ds2.java
Line 44
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Outline
StaticCharMetho
ds2.java
Line 64
container.add( toChar );
container.add( toInt );
setSize( 275, 150 ); // set the window size
setVisible( true );
// show the window
}
76
77
78
79
80
81
82
83
84
Outline
StaticCharMetho
ds2.java
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
OtherCharMethod
s.java
Lines 12-15
Characters non-static methods
charValue, toString and equals
if ( c1.equals( c2 ) )
output += "\n\nc1 and c2 are equal";
else
output += "\n\nc1 and c2 are not equal";
JOptionPane.showMessageDialog( null, output,
"Non-static Character methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class OtherCharMethods
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
TokenTest.java
Line 24
25
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
Outline
inputField.addActionListener(
new ActionListener() {
Line 33
Line
Count number
of36
tokens
Lines 38-39
while ( tokens.hasMoreTokens() )
outputArea.append( tokens.nextToken() + "\n" );
}
} // end anonymous inner class
54
55
56
57
58
59
60
61
62
// execute application
public static void main( String args[] )
{
TokenTest application = new TokenTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
TokenTest.java
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
Outline
DeckOfCards.jav
a
Lines 19 and 29
Line 30
Deck of 52 Cards
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
// anonymous inner
Outline
Fill deck array with Cards
DeckOfCards.jav
a
Lines 27-29
Line 43
if ( dealt != null ) {
displayField.setText( dealt.toString() );
statusLabel.setText( "Card #: " + currentCard );
}
else {
displayField.setText( "NO MORE CARDS TO DEAL" );
statusLabel.setText( "Shuffle cards to continue" );
}
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
Outline
DeckOfCards.jav
a
container.add( dealButton );
Line 70
// shuffle deck
public void actionPerformed( ActionEvent actionEvent )
{
displayField.setText( "SHUFFLING ..." );
shuffle();
displayField.setText( "DECK IS SHUFFLED" );
}
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Outline
DeckOfCards.jav
a
Lines 92-102
}
// shuffle deck of cards with one-pass algorithm
private void shuffle()
{
currentCard = -1;
// for each card, pick another random card and swap them
for ( int first = 0; first < deck.length; first++ ) {
int second = ( int ) ( Math.random() * 52 );
Card temp = deck[ first ];
deck[ first ] = deck[ second ];
deck[ second ] = temp;
}
Outline
104
dealButton.setEnabled( true );
105
}
106
107
// deal one card
DeckOfCards.jav
108
private Card dealCard()
If deck is not empty, a Card
a
109
{
object reference is returned;
110
if ( ++currentCard < deck.length )
otherwise, null is returnedLines 108-116
111
return deck[ currentCard ];
112
else {
113
dealButton.setEnabled( false );
Lines 114 and 123
Method setEnabled enables
114
return null;
and disables JButton
115
}
116
}
117
118
// execute application
119
public static void main( String args[] )
120
{
121
DeckOfCards application = new DeckOfCards();
122
123
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
124
}
125
126 } // end class DeckOfCards
127
Outline
DeckOfCards.jav
a
Lines 130-131
Class Pattern
An immutable regular expression
Class Match
Character
\d
Matches
Matches
any digit
Character
\D
\w
\W
\s
any whitespace
\S
any non-whitespace
any non-digit
Quantifier
Matches
{n}
{n,}
{n,m}
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
ValidateFrame.j
ava
25
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
Outline
okButton.addActionListener(
new ActionListener() { // inner class
ValidateFrame.j
ava
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Outline
ValidateFrame.j
ava
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
container.add(
container.add(
container.add(
container.add(
container.add(
container.add(
Outline
firstName );
lastName );
address1 );
address2 );
phone );
ok );
ValidateFrame.j
ava
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
Outline
ValidateFrame.j
ava
Lines 109-118
Outline
121
// if city format invalid show message
122
else if ( !cityTextField.getText().matches(
123
"([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ) )
124
JOptionPane.showMessageDialog( this, "Invalid city" );
ValidateFrame.j
125
ava
126
// if state format invalid show message
127
else if ( !stateTextField.getText().matches(
Lines 122-137
128
"([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ) )
Matches returns true if the
129
JOptionPane.showMessageDialog( this, "Invalid state" );
130
String matches the regular
131
// if zip code format invalid show message
expression
132
else if ( !zipTextField.getText().matches( "\\d{5}" ) )
133
JOptionPane.showMessageDialog( this, "Invalid zip code" );
134
135
// if phone number format invalid show message
136
else if ( !phoneTextField.getText().matches(
137
"[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}" ) )
138
JOptionPane.showMessageDialog( this, "Invalid phone number" );
139
140
else // information is valid, signal user
141
JOptionPane.showMessageDialog( this, "Thank you" );
142
143
} // end method validateDate
144
145 } // end class ValidateFrame
Outline
ValidateFrame.j
ava
Error message if
TextBox left blank
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
RegexSubstituti
Line 20
Line 26
Replace every instance of stars
in firstString with carets
);
in
firstString with word
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
Outline
Line 38
Outline
RegexSubstituti
on.java
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
Outline
RegexMatches.ja
va
Lines 13-14
compile creates an immutable
Line 22
regular expression object
Line 24
Line 25
a Pattern
26
27
28
29
30
31
32
Outline
RegexMatches.ja
va
} // end main
} // end class RegexMatches
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Outline
// ElevatorSimulationEvent.java
// Basic event packet holding Location object
package com.deitel.jhtp5.elevator.event;
ElevatorSimulat
ionEvent.java
// Deitel packages
import com.deitel.jhtp5.elevator.model.*;
public class ElevatorSimulationEvent {
Represents an event
in elevator simulation
Line 8
Line 11
Location object reference
represents location where even
was generated Line 14
Object object reference represents
object that generated event
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Outline
ElevatorSimulat
ionEvent.java
Solution:
ElevatorSimulationEvent
BellEvent
DoorEvent
LightEvent
PersonMoveEvent
ButtonEvent
ElevatorMoveEvent
ButtonEvent
Button
Button
Door
Door
Light
DoorEvent
LightEvent
PersonMoveEvent
ElevatorMoveEvent
Person
Elevator
Include notes
Explanatory remarks about UML graphics
Represented as rectangles with corners folded over
All interactions happen on first Floor
Eliminates naming ambiguity
Include events
Elevator informs objects of action that has happened
Elevator notifies object of arrival
3.2 : openDoor( )
firstFloorDoor : Door
4.1.1 : resetButton( )
firstFloorButton : Button
4.2.1 : turnOnLight( )
: ElevatorShaft
4.1 :
elevatorArrived( Elevato
rMoveEvent )
firstFloorLight: Light
waitingPassenger : Person
ridingPassenger : Person
: Elevator
ev
at
1
e :
or leva
M to
o v rA
e E rr
ve ive
nt d(
) El
1.1: resetButton( )
3.3.1 : exitElevator( )
a
ev
El
d(
ve )
rri n t
rA e
t o Ev
:
3 leva ove
e rM
to
elevatorButton: Button
2:
elevatorArrived( Elevato
rMoveEvent )
3.2.1.1 : enterElevator( )
: Bell
2.1: ringBell( )
3.3 : doorOpened( )
: ElevatorDoor
Method elevatorArrived
Invoked when Elevator arrives
Method elevatorDeparted
Invoked when Elevator departs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Outline
// ElevatorMoveEvent.java
// Indicates on which Floor the Elevator arrived or departed
package com.deitel.jhtp5.elevator.event;
ElevatorMoveEve
nt.java
// Deitel package
import com.deitel.jhtp5.elevator.model.*;
public class ElevatorMoveEvent extends ElevatorSimulationEvent {
// ElevatorMoveEvent constructor
public ElevatorMoveEvent( Object source, Location location )
{
super( source, location );
}
}
1
2
3
4
5
6
7
8
9
10
11
12
Outline
// ElevatorMoveListener.java
// Methods invoked when Elevator has either departed or arrived
package com.deitel.jhtp5.elevator.event;
ElevatorMoveLis
tener.java
Signals (events)
e.g., Elevator signals arrival to Light
Self associations
e.g., Light turns itself on and off
Door
1
Signalsar
rival
Turns
on/off
Light
Resets
1
Signals
arrival
Opens /
Closes
Signals arrival
ElevatorShaft
Button
Presses
1
Informs of
opening
Person
1
Opens/Closes
1
1
1
Elevator
ElevatorDoor
Signals
arrival
1
1
1
Signals
arrival
Rings
Signals to
move
Bell
1
1
Occupies
Signals
arrival
Location
Floor