开课吧Java课堂之什么是搜索字符串

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值