1.indexOf (String str) 从字符串开始(索引为0)位置,寻找相应的子字符串,返回第一次出现的索引位置。否则返回-1,
方向从左往右找。
2.indexOf(String str, int fromIndex) 从指定索引开始(包括指定位置),寻找相应的子字符串,返回第一次出现的索引位置。
否则返回-1,方向从左往右找。
3.lastIndexOf (String str)从字符串末尾(索引为字符串长度-1)位置,寻找相应的子字符串,返回最后一次出现的索引位置。
否则返回-1,方向从右向左。
4.lastIndexOf (String str,int fromIndex)从字符串指定位置,寻找相应的子字符串,返回最后一次出现的索引位置。
否则返回-1,方向从右向左。
注:lastIndexOf(String str ,int fromIndex)容易出错,可以理解为0-fromIndex(包括该位置)这段字符串中,最后一次出现子字符串的位置。
package com;
public class test {
public static void main(String[] args) {
String str="123456789123456789";
int posLast=str.lastIndexOf("1"); //9
int posLast1=str.lastIndexOf("1",11);//9
int posLast2=str.lastIndexOf("1",8);//0
int pos=str.indexOf("1");//0
int pos1=str.lastIndexOf("1",0);//0
int pos2=str.lastIndexOf("1",9);//9
System.out.println("last**************");
System.out.println(posLast);
System.out.println(posLast1);
System.out.println(posLast2);
System.out.println("first*************");
System.out.println(pos);
System.out.println(pos1);
System.out.println(pos2);
}
}
Java String查找方法详解
本文详细介绍了Java中String类的查找方法,包括indexOf和lastIndexOf的使用方式及其参数含义。通过具体的示例代码展示了如何从字符串中定位子字符串的位置,无论是从左到右还是从右到左进行搜索。
1211

被折叠的 条评论
为什么被折叠?



