java indexof 的末尾_java indexOf() lastIndexOf() 字符串查找函数

利用indexOf()匹配字符串

返回 String 对象内第一次出现子字符串的字符位置。

strObj.indexOf(subString[, startIndex])

参数

strObj

必选项。String 对象或文字。

subString

必选项。要在 String 对象中查找的子字符串。

starIndex

可选项。该整数值指出在 String 对象内开始查找的索引。如果省略,则从字符串的开始处查找。

说明

indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。

如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

public class MainClass{

public static void main(String[] arg){

String str = "abcde";

int index = 0;

index = str.indexOf('c');

System.out.println(index);

}

}

实例二

public class MainClass{

public static void main(String[] arg){

String str = "abcdea";

int index = 0;

index = str.lastIndexOf('a');

System.out.println(index);

}

}

搜索指定字符所在字符串中的位置

public class MainClass{

public static void main(String[] arg){

String str = "abcdea";

int startIndex = 3;

int index = 0;

index = str.indexOf('a', startIndex);

System.out.println(index);

}

}

字符串最后面出来

public   int   lastIndexOf(String   str,   int   fromIndex)

//从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

//   k   <=   Math.min(fromIndex,   str.length())   &&   this.startsWith(str,   k)

//   就是在String中查找str出现的最后一次位置!如果位置 <=fromIndex就返回,否则返回-1

对你的情景就是:

//   banner中最后一次出现One的位置在9

//并且9 <10所以返回9

public class MainClass{

public static void main(String[] arg){

String str = "abcdeabcdef";

int index = 0;

index = str.lastIndexOf("ab");

System.out.println(index);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值