的以下方法都可以:
public int indexOf(String str)
参数:
str - 任意字符串。
返回:
如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这种子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1。
public int indexOf(String str,int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
参数:
str - 要搜索的子字符串。
fromIndex - 开始搜索的索引位置。
返回:
指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
public int lastIndexOf(String str)
返回指定子字符串在此字符串中最右边出现处的索引。将最右边的空字符串 "" 视为出现在索引值 this.length() 处。
参数:
str - 要搜索的子字符串。
返回:
如果字符串参数作为一个子字符串在此对象中出现一次或多次,则返回最后一个这种子字符串的第一个字符。如果它不作为一个子字符串出现,则返回 -1。
public int lastIndexOf(String str,int fromIndex)
返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
参数:
str - 要搜索的子字符串。
fromIndex - 开始搜索的索引位置。
返回:
指定子字符串在此字符串中最后一次出现处的索引。
Java中字符串中子串的查找共有四种方法,如下:1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。
2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。
4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
示例
下面的示例说明了 indexOf 方法的用法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function IndexDemo(str2){
var str1 = "BABEBIBOBUBABEBIBOBU"
var s = str1.indexOf(str2)
return(s)
}
public class FirstDemo {
/**
*API中String的常用方法
*/
// 查找指定字符串是否存在
public static void main(String[] args) {
String str1 = "abcdefghijklmnabc"
// 从头开始查找是否存在指定的字符
System.out.println(str1.indexOf("c"))
// 从第四个字符位置开始往后继续查找
System.out.println(str1.indexOf("c", 3))
//若指定字符串中没有该字符则系统返回-1
System.out.println(str1.indexOf("x"))
}