Introduction
String.contains()方法是Java中一个常用的字符串操作方法。该方法用于判断一个字符串是否包含另外一个字符串。在这篇文章中,我们将会探讨该方法的使用和相关实践。
Working with contains()
1.使用contains()方法检查字符串是否包含一个子串
public static void main(String[] args) {
String str = "Learn Java programming";
boolean result = str.contains("Java");
System.out.println("Does str contain Java? " + result);
}
运行该方法将会得到如下输出:
Does str contain Java? true
2.contains()方法在检查字符串时不区分大小写
String greeting = "Hello World";
if (greeting.contains("world")) {
System.out.println("Found world");
} else {
System.out.println("Did not find world");
}
运行该方法得到如下输出:
Found world
因为contains()方法不区分大小写,所以包含“World”子串的“Hello World”字符串被视为包含“world”。
3.使用contains()方法检查多个子串是否存在
String str = "The quick brown fox jumps over the lazy dog";
boolean result = str.contains("quick") && str.contains("dog");
System.out.println("Does str contain quick and dog? " + result);
运行该方法会得到如下输出:
Does str contain quick and dog? true
在该示例中,contains()方法被用于判断字符串“str”是否同时包含两个不同的子串。结果表明,该字符串确实包含“quick”和“dog”两个子串。
4.使用contains()方法与正则表达式结合
contains()方法可以与正则表达式结合使用,这样可以检查字符串中是否存在符合特定模式的文本。
String str = "This is a demo string";
boolean result = str.contains("\\bdemo\\b");
if (result) {
System.out.println("The string contains demo");
} else {
System.out.println("The string does not contain demo");
}
运行该方法得到如下输出:
The string contains demo
在该示例中,contains()方法被用于检查字符串中是否存在一个独立的“demo”单词。为了实现这个目标,使用了“\\b”元字符来匹配单词的边界。
结论
Java中的String.contains()方法是一个非常实用的方法,用于检查一个字符串中是否包含另外一个字符串或模式。在编写代码时,要使用该方法的不同方式和各种用例,可以为程序员节省大量的时间和精力。