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

Java中如何使用函数检查一个字符串是否包含特定的子字符串

发布时间:2023-06-25 11:14:35

在Java中,可以使用String类提供的indexOf()函数来检查一个字符串中是否包含特定的子字符串。

语法如下:

public int indexOf(String str)

该函数接受一个参数str,表示待查找的子字符串。如果该字符串包含子字符串,indexOf()函数返回子字符串在字符串中 次出现的位置;如果没有找到子字符串,返回-1。

例如,可以使用以下代码检查字符串"Hello World"是否包含子字符串"World":

String str = "Hello World";
if (str.indexOf("World") != -1) {
    System.out.println("包含子字符串World");
} else {
    System.out.println("不包含子字符串World");
}

该代码输出"包含子字符串World",因为字符串"Hello World"中包含子字符串"World"。

需要注意的是,indexOf()函数区分大小写。如果需要忽略大小写,可以使用equalsIgnoreCase()函数,例如:

String str = "Hello World";
if (str.toLowerCase().indexOf("world") != -1) {
    System.out.println("包含子字符串World");
} else {
    System.out.println("不包含子字符串World");
}

该代码也会输出"包含子字符串World",因为它忽略了字符串大小写。

除了indexOf()函数,String类还提供了其他相关函数,如lastIndexOf()、contains()等,也可以用来检查字符串是否包含特定的子字符串。需要根据实际需求选择适合的函数使用。