Java Reference
In-Depth Information
Function substring
For
s
a string, the call
s.substring(h,k)
yields the value
s[h..k - 1]
.
Yes, that is right; character
s[k]
is not included in the substring
s.substring
[h,k]
. Arguments
h
and
k
must satisfy:
h
is the index of some character of
s
:
0 ≤ h < s.length()
.
k
satisfies:
h ≤ k ≤ s.length()
.
Note:
s.substring(h,h)
denotes the empty string of
s
beginning at index
h
.
Equality of strings
When testing for equality, the important thing to remember is that a
String
value is an object. Consider
String
variables
s
and
t
as shown here:
Activity
5-3.6
a6
a7
s 6
String
String
t 7
"Yes."
"Yes."
The expression
s==t
yields
false
, even though folders
a6
and
a7
contain the
same value because expression
s==t
compares the values in
s
and
t
, which are
different. To compare the contents of folders, use instance function
equals
:
s.equals(t)
or
t.equals(s)
Both calls shown above yield
true
. Here is a call that would yield
false
:
"yeS.".equals(s)
Other methods of class String
Class
String
has several instance functions and one static function. We list
function calls to some of them below, with brief explanations. Look at the API
specs for
String
for more explanation. Below,
p
and
q
are
String
s.
•
p.compareTo(s): = -1
,
0
, or
1
depending on whether
p<
,
=
, or
>s
•
p.endsWith(s): =
“
s
is a suffix of
p
”
•
p.indexOf(s): =
index of first occurrence of
s
in
p
(
-1
if none)
•
p.lastIndexOf(s): =
index of last occurrence of
s
in
p
(
-1
if none)
•
p.startsWith(s): =
“
s
is a prefix of
p
”
•
p.toLowerCase(): =
copy of
p
with all letters in upper case
•
p.toUpperCase(): =
copy of
p
with all letters in lower case
•
p.trim(): =
copy of
p
with blanks at the start and end removed
•
String.valueOf(x): = x
represented as a
String
.
x
can be any type
Lesson 5-3
goes into more
detail in ex-
plaining these
methods.
5.2.3
Changing a name format
Suppose string
p
contains a name in the format “last-name
,
first-name”, with
exactly one blank after the comma. The letters may be in upper or lower case.
Search WWH ::
Custom Search