public class StringContainsExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, world!";
// 判断字符串是否包含特定字符或子字符串
// 使用 contains 方法
boolean containsWorld = str.contains("world");
System.out.println("字符串中是否包含 'world': " + containsWorld);
// 使用 indexOf 方法,如果返回值大于等于0,则表示包含该子字符串
int index = str.indexOf("world");
System.out.println("字符串中 'world' 的索引位置: " + (index >= 0 ? "存在" : "不存在"));
// 使用正则表达式匹配
boolean matchesPattern = str.matches(".*world.*");
System.out.println("字符串是否匹配正则表达式 '.*world.*': " + matchesPattern);
}
}
contains 方法:这是最简单的方法,直接判断字符串中是否包含指定的子字符串。返回 true 或 false。indexOf 方法:返回指定子字符串在字符串中首次出现的位置。如果子字符串不存在,则返回 -1。matches 方法和正则表达式来判断字符串是否符合某种模式。这里我们使用了 .*world.* 来匹配任何包含 "world" 的字符串。这些方法可以根据具体需求选择使用。
上一篇:java contains
下一篇:java抽象类
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站