java判断字符串是否包含另外一段字符串
时间: 2023-11-03 12:05:29 浏览: 35
在Java中,可以使用`contains()`方法来判断一个字符串是否包含另一个字符串。示例代码如下:
```java
public class Main {
public static void main(String[] args) {
String str1 = "Hello, World!";
String str2 = "World";
boolean isContains = str1.contains(str2);
System.out.println("字符串str1是否包含字符串str2: " + isContains);
}
}
```
相关问题
Java判断字符串是否包含拼音
可以使用Java的正则表达式来判断字符串中是否包含中文拼音。以下是一个简单的示例代码:
```java
import java.util.regex.Pattern;
public class PinyinChecker {
public static void main(String[] args) {
String str1 = "这是一段包含拼音的字符串,ping yin";
String str2 = "这是一段不包含拼音的字符串";
// 匹配中文拼音的正则表达式
String regex = ".*[a-zA-Z]+.*";
boolean hasPinyin1 = Pattern.matches(regex, str1);
boolean hasPinyin2 = Pattern.matches(regex, str2);
System.out.println("字符串1是否包含拼音:" + hasPinyin1);
System.out.println("字符串2是否包含拼音:" + hasPinyin2);
}
}
```
输出结果为:
```
字符串1是否包含拼音:true
字符串2是否包含拼音:false
```
可以看到,对于包含拼音的字符串,正则表达式匹配的结果为true,不包含拼音的字符串匹配结果为false。
java语言判断一段字符串中是否包含几个字符串
Java中可以使用 `String` 类的 `contains()` 方法来判断一个字符串是否包含另一个字符串。如果需要判断一个字符串中是否包含多个字符串,可以使用类似下面的代码:
```java
String str = "This is a sample string";
if (str.contains("sample") && str.contains("is")) {
System.out.println("包含 sample 和 is");
} else if (str.contains("sample")) {
System.out.println("只包含 sample");
} else if (str.contains("is")) {
System.out.println("只包含 is");
} else {
System.out.println("不包含 sample 和 is");
}
```
上述代码中,我们使用了 `contains()` 方法来判断字符串 `str` 是否包含指定的字符串,如果包含则输出相应的信息。您可以根据需求进行修改。