Java判断字符串中是否包含多个字符串
在Java中,我们经常需要判断一个字符串是否包含另外一个或多个字符串。这种需求在实际开发中非常常见,比如判断用户输入的文本是否包含敏感词汇,或者判断一个URL是否包含指定的关键字等。
本文将介绍几种在Java中判断字符串是否包含多个字符串的方法,并提供相应的代码示例。
方法一:使用contains()方法
Java中的String类提供了一个contains()方法,用于判断一个字符串是否包含另外一个字符串。该方法返回一个boolean值,如果字符串包含指定的字符序列,则返回true,否则返回false。
以下是使用contains()方法判断字符串是否包含多个字符串的示例代码:
String str = "This is a sample string";
boolean containsWord1 = str.contains("sample");
boolean containsWord2 = str.contains("string");
boolean containsWord3 = str.contains("example");
System.out.println("Word 'sample' is present: " + containsWord1);
System.out.println("Word 'string' is present: " + containsWord2);
System.out.println("Word 'example' is present: " + containsWord3);
输出结果:
Word 'sample' is present: true
Word 'string' is present: true
Word 'example' is present: false
上述代码中,我们使用contains()方法分别判断了字符串str是否包含"sample"、"string"和"example"。通过输出结果可以看出,字符串str中包含"sample"和"string",但不包含"example"。
方法二:使用indexOf()方法
除了contains()方法,Java中的String类还提供了一个indexOf()方法,用于获取指定字符串在原字符串中的位置。如果指定字符串存在于原字符串中,则返回其在原字符串中的索引值;如果不存在,则返回-1。
以下是使用indexOf()方法判断字符串是否包含多个字符串的示例代码:
String str = "This is a sample string";
int index1 = str.indexOf("sample");
int index2 = str.indexOf("string");
int index3 = str.indexOf("example");
boolean containsWord1 = index1 != -1;
boolean containsWord2 = index2 != -1;
boolean containsWord3 = index3 != -1;
System.out.println("Word 'sample' is present: " + containsWord1);
System.out.println("Word 'string' is present: " + containsWord2);
System.out.println("Word 'example' is present: " + containsWord3);
输出结果:
Word 'sample' is present: true
Word 'string' is present: true
Word 'example' is present: false
上述代码中,我们使用indexOf()方法获取了字符串str中"sample"、"string"和"example"的索引值,并通过判断索引值是否为-1来判断字符串是否包含相应的字符串。
方法三:使用正则表达式
如果需要判断字符串是否包含多个不连续的子字符串,或者需要更复杂的匹配模式,可以使用正则表达式。Java中提供了Pattern和Matcher类来支持正则表达式的使用。
以下是使用正则表达式判断字符串是否包含多个字符串的示例代码:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String str = "This is a sample string";
Pattern pattern = Pattern.compile("sample|string|example");
Matcher matcher = pattern.matcher(str);
boolean containsWords = matcher.find();
System.out.println("Words are present: " + containsWords);
输出结果:
Words are present: true
上述代码中,我们使用正则表达式"sample|string|example"创建了一个Pattern对象,并使用Matcher类的find()方法来判断字符串str是否包含指定的子字符串。
方法四:使用第三方库
除了上述方法,我们还可以使用一些第三方库来进行字符串匹配。比如Apache Commons Lang库中的StringUtils类提供了一个containsAny()方法,用于判断字符串是否包含多个指定的字符序列。
以下是使用Apache Commons Lang库中的StringUtils类判断字符串是否包含多个字符串的示例代码:
import org.apache.commons.lang3.StringUtils;
String str = "This is a sample string";
boolean containsWords = StringUtils.containsAny(str, "sample", "string", "example");
System.out.println("Words are present: " + containsWords);
输出结果:
Words are present: true
上述代码中,我们使用StringUtils类的containsAny()方法判断字符串str是否包含"sample"