欢迎访问宙启技术站
智能推送

如何使用Java函数在字符串中查找指定子字符串?

发布时间:2023-06-18 10:50:12

在 Java 中,有许多可以用来查找指定子字符串的函数。下面将介绍几个常用的函数和使用它们的方法。

1. indexOf()

indexOf() 函数可以在字符串中查找指定的子字符串,并返回第一次出现的位置。例如:

String str = "hello world!";
int index = str.indexOf("world");

此时,index 的值为 6,因为子字符串 "world" 在字符串中从第七个位置开始。如果子字符串不存在,则返回 -1。例如:

String str = "hello world!";
int index = str.indexOf("java");

此时,index 的值为 -1。

2. lastIndexOf()

与 indexOf() 类似,lastIndexOf() 函数可以在字符串中查找指定的子字符串,并返回最后一次出现的位置。例如:

String str = "hello world!";
int index = str.lastIndexOf("l");

此时,index 的值为 9,因为子字符串 "l" 在字符串中最后一次出现在第十个位置上。如果子字符串不存在,则返回 -1。例如:

String str = "hello world!";
int index = str.lastIndexOf("java");

此时,index 的值为 -1。

3. contains()

contains() 函数可以检查字符串中是否包含指定的子字符串。例如:

String str = "hello world!";
if (str.contains("world")) {
    System.out.println("字符串包含子字符串");
} else {
    System.out.println("字符串不包含子字符串");
}

此时,会输出 "字符串包含子字符串"。如果子字符串不存在,则返回 false。

4. startsWith() 和 endsWith()

startsWith() 函数可以检查字符串是否以指定的子字符串开头,endsWith() 函数则可以检查字符串是否以指定的子字符串结尾。例如:

String str = "hello world!";
if (str.startsWith("hel")) {
    System.out.println("字符串以 hel 开头");
} else {
    System.out.println("字符串不以 hel 开头");
}
if (str.endsWith("ld!")) {
    System.out.println("字符串以 ld! 结尾");
} else {
    System.out.println("字符串不以 ld! 结尾");
}

此时,会输出 "字符串以 hel 开头" 和 "字符串以 ld! 结尾"。如果不符合条件,则返回 false。

5. split()

split() 函数可以将字符串按照指定的分隔符拆分成一个字符串数组。例如:

String str = "a,b,c,d,e,f";
String[] arr = str.split(",");
for (String s : arr) {
    System.out.println(s);
}

此时,会输出:

a
b
c
d
e
f

6. substring()

substring() 函数可以截取字符串中指定位置的子串。例如:

String str = "hello world!";
String s = str.substring(6);
System.out.println(s);

此时,会输出 "world!",因为截取的子串从第七个字符开始。如果要截取两个位置之间的子串,可以传入两个参数,表示起始位置和结束位置(不包含结束位置的字符)。例如:

String str = "hello world!";
String s = str.substring(6, 11);
System.out.println(s);

此时,会输出 "world",因为截取的子串从第七个字符开始,一直到第十一个字符。

以上就是一些常用的 Java 函数在字符串中查找指定子字符串的方法,相信对于初学者来说会有所帮助。