怎么用java的contains方法
时间: 2023-06-09 19:07:44 浏览: 35
可以使用以下代码来调用java中的contains方法,来检查一个字符串中是否包含另一个字符串:
```
String str = "Hello world";
String substr = "world";
if (str.contains(substr)) {
System.out.println("Substring found in the given string.");
} else {
System.out.println("Substring not found in the given string.");
}
```
以上代码会输出 "Substring found in the given string." 因为字符串 "world" 存在于字符串 "Hello world" 中。
相关问题
java contains方法的使用、
Java中的`contains()`方法是用于检查字符串中是否包含指定的字符序列。该方法返回一个布尔值,如果字符串包含指定的字符序列,则返回true,否则返回false。
`contains()`方法的语法如下:
```java
public boolean contains(CharSequence sequence)
```
其中,`sequence`参数是要检查的字符序列。
下面是一个示例代码:
```java
String str1 = "Hello World!";
String str2 = "World";
if (str1.contains(str2)) {
System.out.println("字符串包含指定的字符序列");
} else {
System.out.println("字符串不包含指定的字符序列");
}
```
在上面的代码中,我们定义了两个字符串`str1`和`str2`,然后使用`contains()`方法检查`str1`是否包含`str2`,最后根据结果输出相应的提示信息。
输出结果为:"字符串包含指定的字符序列"。
java contains方法多个元素
可以使用Java中的Arrays类中的静态方法contains()来判断一个数组中是否包含指定的元素。如果数组中包含该元素,则返回true;否则返回false。以下是一个示例代码:
```java
import java.util.Arrays;
public class ContainsExample {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange"};
boolean result1 = Arrays.asList(array).contains("apple");
boolean result2 = Arrays.asList(array).contains("grape");
System.out.println(result1); // true
System.out.println(result2); // false
}
}
```
在上面的示例中,我们使用Arrays.asList()方法将数组转换为列表,并使用contains()方法判断元素是否存在于列表中。注意,contains()方法只适用于对象数组,对于基本数据类型的数组,需要使用相应的包装类来进行转换。