// 示例代码:Java 字符串匹配
public class StringMatchExample {
public static void main(String[] args) {
// 定义源字符串
String source = "Hello, welcome to the world of Java!";
// 定义要匹配的子字符串
String target = "Java";
// 使用 contains 方法检查源字符串是否包含目标子字符串
if (source.contains(target)) {
System.out.println("源字符串中包含目标子字符串: " + target);
} else {
System.out.println("源字符串中不包含目标子字符串: " + target);
}
// 使用 indexOf 方法查找子字符串的位置
int index = source.indexOf(target);
if (index != -1) {
System.out.println("目标子字符串 " + target + " 在源字符串中的位置是: " + index);
} else {
System.out.println("源字符串中不包含目标子字符串: " + target);
}
// 使用 matches 方法进行正则表达式匹配
String regex = ".*Java.*";
if (source.matches(regex)) {
System.out.println("源字符串符合正则表达式: " + regex);
} else {
System.out.println("源字符串不符合正则表达式: " + regex);
}
}
}
true
或 false
。-1
。true
或 false
。通过这些方法,可以实现不同场景下的字符串匹配需求。
上一篇:java定义
下一篇:java获取月份最后一天
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站