Java函数:如何查找子字符串在字符串中的位置
发布时间:2023-06-29 16:03:44
在Java中,可以使用String类的indexOf()方法来查找子字符串在字符串中的位置。该方法的语法如下:
int indexOf(String str)
该方法接受一个参数,即要查找的子字符串,返回子字符串在原字符串中的位置,如果找不到该子字符串,则返回-1。
以下是一个示例代码:
public class Main {
public static void main(String[] args) {
String str1 = "Hello World!";
String str2 = "World";
// 使用indexOf()方法查找子字符串的位置
int position = str1.indexOf(str2);
if (position != -1) {
System.out.println("子字符串的位置是:" + position);
} else {
System.out.println("找不到子字符串!");
}
}
}
输出结果为:子字符串的位置是:6
上述代码中,我们首先定义了两个字符串str1和str2,分别为源字符串和要查找的子字符串。然后使用indexOf()方法查找子字符串的位置,并将结果赋值给position变量。最后,根据position的值判断是否找到了子字符串。
请注意,indexOf()方法默认从字符串的开头开始查找子字符串,如果想要从指定位置开始查找,可以使用indexOf(String str, int fromIndex)方法。
int indexOf(String str, int fromIndex)
该方法接受两个参数,第一个参数为要查找的子字符串,第二个参数为查找的起始位置(从0开始),返回子字符串在原字符串中的位置,如果找不到该子字符串,则返回-1。
以下是一个示例代码:
public class Main {
public static void main(String[] args) {
String str1 = "Hello World!";
String str2 = "l";
// 使用indexOf()方法从指定位置开始查找子字符串的位置
int position = str1.indexOf(str2, 3);
if (position != -1) {
System.out.println("子字符串的位置是:" + position);
} else {
System.out.println("找不到子字符串!");
}
}
}
输出结果为:子字符串的位置是:9
上述代码中,我们指定从索引3开始查找子字符串"l",并将结果赋值给position变量。最后,根据position的值判断是否找到了子字符串。
