Java Reference
In-Depth Information
compareToIgnoreCase
methods ignore the case of the letters when comparing two strings.
The
regionMatches
method compares portions of two strings for equality. You can also use
str.startsWith(prefix)
to check whether string
str
starts with a specified prefix, and
str.endsWith(suffix)
to check whether string
str
ends with a specified suffix.
9.2.4 Getting String Length and Characters, and Combining
Strings
The
String
class provides the methods for obtaining a string's length, retrieving individual
characters, and concatenating strings, as shown in Figure 9.3.
java.lang.String
+length(): int
+charAt(index: int): char
+concat(s1: String): String
Returns the number of characters in this string.
Returns the character at the specified index from this string.
Returns a new string that concatenates this string with string
s1
.
F
IGURE
9.3
The
String
class contains the methods for getting string length, individual characters, and combining strings.
You can get the length of a string by invoking its
length()
method. For example,
message.length()
returns the length of the string
message
.
length()
Caution
length
is a method in the
String
class but is a property of an array object. Therefore,
you have to use
s.length()
to get the number of characters in string
s
, and
a.length
to get the number of elements in array
a
.
string length vs. array length
The
s.charAt(index)
method can be used to retrieve a specific character in a string
s
,
where the index is between
0
and
s.length()-1
. For example,
message.charAt(0)
returns the character
W
, as shown in Figure 9.4.
charAt(index)
Note
When you use a string, you often know its literal value. For convenience, Java allows you
to use the string literal to refer directly to strings without creating new variables. Thus,
"Welcome to Java".charAt(0)
is correct and returns
W
.
string literal
Indices
message
0123456789 0 1 2 3 4
We l
come
t
o
Java
message.charAt(0)
message.length() is 15
message.charAt(14)
F
IGURE
9.4
The characters in a
String
object are stored using an array internally.
Note
The
String
class uses an array to store characters internally. The array is private and
cannot be accessed outside of the
String
class. The
String
class provides many
public methods, such as
length()
and
charAt(index)
, to retrieve the string infor-
mation. This is a good example of encapsulation: the data field of the class is hidden
from the user through the private modifier, and thus the user cannot directly manipulate
it. If the array were not private, the user would be able to change the string content by
modifying the array. This would violate the tenet that the
String
class is immutable.
encapsulating string