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

Java函数如何实现判断一个字符串是否包含另一个字符串?

发布时间:2023-06-19 05:58:11

在Java中,判断一个字符串是否包含另一个字符串可以使用String类的方法实现。

1. contains()方法

可以使用contains()方法来判断一个字符串是否包含另一个字符串, 它的语法格式如下:

public boolean contains(CharSequence sequence)

示例代码:

String str1 = "Hello world!";
String str2 = "world";
if(str1.contains(str2)){
    System.out.println(str2 + " is contained in " + str1);
}

2. indexOf()方法

使用indexOf()方法可以查找一个字符串在另一个字符串中的位置,如果找到了,返回对应的位置,否则返回-1。所以,可以用indexOf()方法来判断一个字符串是否包含另一个字符串。

示例代码:

String str1 = "Hello world!";
String str2 = "world";
if(str1.indexOf(str2) != -1){
    System.out.println(str2 + " is contained in " + str1);
}

3. matches()方法

使用matches()方法可以判断一个字符串是否匹配一个正则表达式。如果匹配,返回true;否则,返回false。因此,可以使用matches()方法来判断一个字符串是否包含另一个字符串。

示例代码:

String str1 = "Hello world!";
String str2 = "world";
if(str1.matches(".*" + str2 + ".*")){
    System.out.println(str2 + " is contained in " + str1);
}

其中,“.*”表示匹配任意字符的任意次数。

综上,以上三种方法都可以判断一个字符串是否包含另一个字符串,可以根据具体的场景选择使用哪种方法。