contains()函数:用法和示例
contains()函数是Java中String类中的方法之一。它用于检查一个字符串是否包含另一个字符串,并返回一个布尔值,指示是否找到了子字符串。本文将介绍contains()函数的用法和示例。
用法
contains()函数在String类中定义为:
public boolean contains(CharSequence str)
该函数使用一个CharSequence对象作为其参数。CharSequence是一个接口,它可以被字符串等类实现。因此,使用contains()函数时可以传递任何实现该接口的类的实例。该函数返回一个布尔值,指示调用它的字符串中是否包含指定的CharSequence。
另外,contains()函数还可以用于指示一个字符串是否包含一个字符。此时,可以通过将字符转换为字符串传递给该函数来实现。
示例
以下是一些使用contains()函数的示例:
1. 检查一个字符串是否包含另一个字符串:
String str1 = "hello world"; String str2 = "world"; boolean result = str1.contains(str2); // 返回true
在此示例中,contains()函数用于检查str1是否包含str2。由于str2是str1的一个子字符串,因此contains()函数返回true。
2. 检查一个字符串是否包含一个字符:
String str = "aliceinwonderland";
boolean result = str.contains("a"); // 返回true
在此示例中,使用contains()函数检查字符串str是否包含字符"a"。由于str中包含字符"a",因此contains()函数返回true。
3. 检查一个字符串是否包含另一个字符串的一部分:
String str = "the quick brown fox jumps over the lazy dog";
boolean result = str.contains("fox jumps"); // 返回true
在此示例中,使用contains()函数检查字符串str是否包含“fox jumps”这个子字符串。由于str中包含这个子字符串,因此contains()函数返回true。
4. 检查一个字符串是否包含另一个字符串,并忽略大小写:
String str1 = "hello world"; String str2 = "WORLD"; boolean result = str1.toLowerCase().contains(str2.toLowerCase()); // 返回true
在此示例中,contains()函数用于检查str1是否包含str2。由于str2是str1的一个子字符串,但它的大小写可能不同,因此需要将它们都转换为小写字母。最后,由于str1包含str2的小写字母版本,因此contains()函数返回true。
总结
contains()函数是一种非常有用的函数,可以用于检查一个字符串是否包含另一个字符串或字符。通过阅读本文所提供的示例,您应该能够了解contains()函数的基本用法并成功地在您的代码中使用它。
