Java Reference
In-Depth Information
8
String s1 =
"hello"
;
9
String s2 =
"GOODBYE"
;
10
String s3 =
" spaces "
;
11
12
System.out.printf(
"s1 = %s%ns2 = %s%ns3 = %s%n%n"
, s1, s2, s3);
13
14
// test method replace
15
System.out.printf(
16
"Replace 'l' with 'L' in s1: %s%n%n"
,
s1.replace(
'l'
,
'L'
)
);
17
18
// test toLowerCase and toUpperCase
19
System.out.printf(
"s1.toUpperCase() = %s%n"
,
s1.toUpperCase()
s2.toLowerCase()
);
20
System.out.printf(
"s2.toLowerCase() = %s%n%n"
,
);
21
22
// test trim method
23
System.out.printf(
"s3 after trim = \"%s\"%n%n"
,
s3.trim()
);
24
25
// test toCharArray method
26
char
[] charArray = s1.toCharArray();
27
System.out.print(
"s1 as a character array = "
);
28
29
for
(
char
character : charArray)
30
System.out.print(character);
31
32
System.out.println();
33
}
34
}
// end class StringMiscellaneous2
s1 = hello
s2 = GOODBYE
s3 = spaces
Replace 'l' with 'L' in s1: heLLo
s1.toUpperCase() = HELLO
s2.toLowerCase() = goodbye
s3 after trim = "spaces"
s1 as a character array = hello
Fig. 14.8
|
String
methods
replace
,
toLowerCase
,
toUpperCase
,
trim
and
toCharArray
.
(Part 2 of 2.)
Line 16 uses
String
method
replace
to return a new
String
object in which every
occurrence in
s1
of character
'l'
(lowercase el) is replaced with character
'L'
. Method
replace
leaves the original
String
unchanged. If there are no occurrences of the first argu-
ment in the
String
, method
replace
returns the original
String
. An overloaded version
of method
replace
enables you to replace substrings rather than individual characters.
Line 19 uses
String
method
toUpperCase
to generate a new
String
with uppercase
letters where corresponding lowercase letters exist in
s1
. The method returns a new
String
object containing the converted
String
and leaves the original
String
unchanged. If there
are no characters to convert, method
toUpperCase
returns the original
String
.