Java Reference
In-Depth Information
Now we can write expressions like the following to determine where a particular
character appears in the
String
:
int r = s.indexOf('r');
int v = s.indexOf('v');
This code sets
r
to
3
because 3 is the index of the first occurrence of the letter
'r'
in the
String
. It sets
v
to
17
because that is the index of the first occurrence of the
letter
'
v
'
in the
String
.
The
indexOf
method is part of the
String
class, but let's see how we could write
a different method that performs the same task. Our method would be called differ-
ently because it is a static method outside the
String
object. We would have to pass
it both the
String
and the letter:
int r = indexOf('r', s);
int v = indexOf('v', s);
So, the header for our method would be:
public static int indexOf(char ch, String s) {
...
}
Remember that when a method returns a value, we must include the return type
after the words
public static
. In this case, we have indicated that the method
returns an
int
because the index will be an integer.
This task can be solved rather nicely with a
for
loop that goes through
each possible index from first to last. We can describe this in pseudocode as
follows:
for (each index i in the string) {
if the char is at position i, we've found it.
}
To flesh this out, we have to think about how to test whether the character at posi-
tion
i
is the one we are looking for. Remember that
String
objects have a method
called
charAt
that allows us to pull out an individual character from the
String
,so
we can refine our pseudocode as follows:
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ch) {
we've found it.
}
}
Search WWH ::
Custom Search