is looking for the first occurrence of s1 within s2. In
this example, s1 must be a String, and s2 can be either a String or a char.
The indexOf method returns an int. The value returned is the index of the
first occurrence of s2 within s1 (if s2 is a String, its the index of the
starting character in s2 that is returned). When s2 does not appear in s1,
the returned value is -1. Here are some illustrative examples. Suppose that
s1 is the String "hi there dude, how are you?". This String is printed out
below, with the indexes of its characters printed above.
index
|
0
|
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
|
|
h
|
i
|
|
t
|
h
|
e
|
r
|
e
|
|
d
|
u
|
d
|
e
|
,
|
|
h
|
o
|
w
|
|
a
|
r
|
e
|
|
y
|
o
|
u
|
?
|
s1.indexOf('t') = 3
s1.indexOf("dude") = 9
s1.indexOf("the") = 3
s1.indexOf("Hi") = -1
s1.indexOf('c') = -1
s1.indexOf('e') = 5
If you want to look for Strings or chars, beyond some index, say
from index 5 on, you use
s1.indexOf( s2, 5). Here are some of those
examples:
To find the second occurrence of 'e':
s1.indexOf('e',6)
To find the second "re": s1.indexOf("re", 7) or
s1.indexOf("re", 8)
To find the second 'h' in a tricky manner:
s1.indexOf('h', s1.indexOf('h')
+ 1)
It is common to use indexOf as part of a test, relying on the fact that
when the index of something is -1, it means that thing does not occur in s1.
To see if the string s1 starts with a capital letter, you could use:
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(s1.charAt(0)) >= 0)
outy.printLine("First letter is uppercase");
else
outy.printLine("First letter is not uppercase");
To see if the letter 'a' appears twice in s1:
int loc = s1.indexOf('a'), loc2 = -1;
if (loc >= 0)
if (s1.indexOf('a', loc + 1) >= 0 )
outy.printLine("The letter a appears at least
twice.");
else
outy.printLine("The letter appears exactly
once.");
else
outy.printLine("The letter a does not appear.");