java字符串位置查找的代码实现

本文详细介绍了Java中String类的lastIndexOf和indexOf方法的使用方式及其区别。通过具体的代码示例展示了如何查找字符串中特定子串的位置,并解释了不同参数的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. lastIndexOf(String/int arg0, int arg1) 

  在当前字符串中小于arg1的范围中,查找指定字符串或字符。返回值同样为子串在原串中最后一次出现的相对位置,只不过查找有范围限制,超出范围的部分即便仍有子串,也无法找到。

[java]  view plain  copy
  1. String s = "abcdefgabcdefg";  
  2. int i = s.lastIndexOf("cd",8);  
  3. System.out.println(i);  

运行结果为:

[java]  view plain  copy
  1. 2  

    注意与上一个例子做比较。

    但是当范围当中包含了子串的前面的某一位或某几位时:

[java]  view plain  copy
  1. String s = "abcdefgabcdefg";  
  2. int i = s.lastIndexOf("cd",9);  
  3. System.out.println(i);  

运行结果为:

[java]  view plain  copy
  1. 9  

    原因很简单,字符串比较时约束的范围仅限制住了首地址而没有约束长度。

2. indexOf(String/int arg0)

返回值为源字符串中子串最先出现的位置(参数int arg0同样指字符的ascii码值),若找不到,则返回-1。

indexOf的限制arg1参数限定的是由此位起始搜索lastIndexOf限定的是搜索到此位为止


[java]  view plain  copy
  1. String s = "abcdefgabcdefg";  
  2. int i = s.indexOf("cd",8);       
  3. System.out.println(i);  

运行结果为:

[java]  view plain  copy
  1. 9  

3.实例

lastIndexOf:

public class SearchlastString {
public static void main ( String [ ] args ) {
    String strOrig = " Hello world ,Hello Runoob " ;
int lastIndex = strOrig . lastIndexOf ( " Runoob " ) ;
if ( lastIndex == - 1 ) {
System . out . println ( " 没有找到字符串 Runoob " ) ;
} else {
System . out . println ( " Runoob 字符串最后出现的位置: " + lastIndex ) ;
}
} }

以上代码实例输出结果为:

Runoob 字符串最后出现的位置: 19

indexOf:

public class SearchStringEmp {

public static void main(String[] args) {

String strOrig = "Google Runoob Taobao";

int intIndex = strOrig.indexOf("Runoob");

if(intIndex == - 1){

System.out.println("没有找到字符串 Runoob");

}else{

System.out.println("Runoob 字符串位置 " + intIndex);

}

}}


以上代码实例输出结果为:

Runoob 字符串位置 7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值