查找字符串
indexOf() 方法和 lastlndexOf() 方法在字符串中获取匹配字符(串)的索引值。
- indexOf() 方法返回字符串参数在目标字符串中首次出现的索引位置,如果能找到,则返回索引值,否则返回-1.
str.indexOf(String value);
str.indexOf(String value,int fromIndex);
stri标识目标字符串,value表示需要在目标字符串中查找的字符串,fromIndex表示查找的起始位置,如果不指定,则会从字符串的首位(索引为0开始查找)。
public class dome2{
public static void main(String[] args) {
String str="hello world,hello java";
System.out.println(str.indexOf("he"));
System.out.println(str.indexOf("ll",4));
}
}
结果
0
14
2.lastIndexOf()方法返回字符串参数在目标字符串中最后一次出现的索引位置(从右往左查找),如果能找到则返回索引值,否则返回-1.
str.lastIndexOf(String value)
str.lastlndexOf(String value, int fromIndex)
stri标识目标字符串,value表示需要在目标字符串中查找的字符串,fromIndex表示从右往左查找的起始位置,如果不指定,则会从字符串的末尾查找。
public class dome2{
public static void main(String[] args) {
String str="hello world,hello python,hello java";
System.out.println(str.lastIndexOf("he"));
System.out.println(str.lastIndexOf("he",11));
}
}
结果
25
0
charAt() 方法根据索引查找字符
str.charAt(int index);
str代表目标字符串,index代表需要查找字符的索引。
public class dome2{
public static void main(String[] args) {
String str="hello world!";
System.out.println(str.charAt(str.length()-1));
System.out.println(str.charAt(3));
}
}
结果
!
l