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"))
}
假设你说的第一个字符串是a,第二个是b判断a中是否有一个字符或者一段字符串包含于b中:
boolean
ifcontrain
=
false
for(int
i
=
0
i
<
a.length
-
1
i
++
)
{
for(int
j
=
i
+
1
j
<
a.length
j++
)
{
if(b.contains(a.substring(i
,
j
)))
{
ifcontrain
=
true
}
}
}
最后看ifcontrain是true,则包含,是false,就是不包含。
如果想要看包含的是哪段,就在ifcontrain
=
true一句后面再加一句
输出
a.substring(i
,
j
)
就行了。