java如何判断string
判断字符串的常见方法
在Java中,判断字符串通常涉及检查字符串的内容、长度、格式或与其他字符串的关系。以下是几种常见的判断方法:
检查字符串是否为空或null
String str = "example";
if (str == null || str.isEmpty()) {
// 字符串为null或空
}
检查字符串长度
if (str.length() > 0) {
// 字符串不为空
}
比较字符串内容
String str1 = "hello";
String str2 = "hello";
if (str1.equals(str2)) {
// 字符串内容相同
}
忽略大小写比较

if (str1.equalsIgnoreCase(str2)) {
// 忽略大小写后内容相同
}
检查字符串是否包含特定子串
if (str.contains("world")) {
// 字符串包含"world"
}
检查字符串是否以特定前缀或后缀开头/结尾
if (str.startsWith("http")) {
// 字符串以"http"开头
}
if (str.endsWith(".com")) {
// 字符串以".com"结尾
}
使用正则表达式匹配

if (str.matches("\\d+")) {
// 字符串全部由数字组成
}
字符串判断的最佳实践
-
使用
Objects.equals()避免NullPointerException:if (Objects.equals(str1, str2)) { // 安全比较 } -
对于可能为null的字符串,先检查null再调用方法:
if (str != null && !str.isEmpty()) { // 安全操作 } -
对于大量字符串比较,考虑使用
String.intern()方法:if (str1.intern() == str2.intern()) { // 比较字符串常量池引用 }
这些方法涵盖了Java中判断字符串的大多数常见需求,可以根据具体场景选择合适的方式。






