public class StringContainsExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, world!";
// 使用contains方法判断是否包含指定的字符序列
boolean containsHello = str.contains("Hello");
System.out.println("字符串包含 'Hello' 吗? " + containsHello); // 输出: true
// 使用indexOf方法判断是否包含指定的字符
int index = str.indexOf('w');
if (index != -1) {
System.out.println("字符 'w' 存在于索引位置: " + index); // 输出: 7
} else {
System.out.println("字符 'w' 不存在于字符串中");
}
// 使用charAt方法检查特定位置的字符
char specificChar = str.charAt(0);
System.out.println("索引0处的字符是: " + specificChar); // 输出: H
// 使用matches方法判断是否符合正则表达式
boolean matchesPattern = str.matches(".*world.*");
System.out.println("字符串是否包含 'world'? " + matchesPattern); // 输出: true
}
}
contains
方法:用于检查字符串是否包含指定的字符序列。返回 true
或 false
。indexOf
方法:用于查找指定字符在字符串中的索引位置,如果找不到则返回 -1
。charAt
方法:用于获取指定索引位置的字符。matches
方法:用于检查字符串是否匹配给定的正则表达式。这些方法可以帮助你判断字符串中是否包含特定的字符或字符序列。
上一篇:java判断字符串包含某个字符
下一篇:java线程池参数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站