String类提供了两个方法,允许在字符串中搜索指定的字符或子字符串:
· indexOf( ) 搜索字符或子字符串首次出现。
· lastIndexOf( ) 搜索字符或子字符串的最后一次出现。
这两种方法被几种不同的方法重载。在所有这些情况下,方法返回字符或子字符串被发现的位置的下标,当搜索失败时,返回-1。
搜索字符首次出现用
int indexOf(int ch)
搜索字符最后一次出现用
int lastIndexOf(int ch)
这里ch是被查找的字符。
搜索子字符串首次或最后一次出现用
int indexOf(String str)
int lastIndexOf(String str)
这里子字符串由str指定可以使用如下这些形式指定搜索的起始点:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
这里startIndex指定了搜索开始点的下标。对于indexOf( )方法,搜索从startIndex开始到字符串结束。对于lastIndexOf( )方法,搜索从startIndex开始到下标0。
下面的例子说明如何利用不同的索引方法在字符串(String)的内部进行搜索:
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}
下面是该程序的输出结果:
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55