Java常用的字符串工具方法有很多,以下是一些常见的封装:
- 判断字符串是否为空或null
public static boolean isNullOrEmpty(String str) {return str == null || str.trim().isEmpty();
}
- 判断字符串是否为数字
public static boolean isNumeric(String str) {if (isNullOrEmpty(str)) {return false;}try {Double.parseDouble(str);return true;} catch (NumberFormatException e) {return false;}
}
- 去除字符串中的空格
public static String trim(String str) {if (isNullOrEmpty(str)) {return str;}return str.trim();
}
- 拼接字符串
public static String join(String separator, String... strings) {StringBuilder sb = new StringBuilder();for (int i = 0; i < strings.length; i++) {if (i > 0) {sb.append(separator);}sb.append(strings[i]);}return sb.toString();
}
- 搜索指定字符串在原字符串中出现的次数
public static int countMatches(String str, String sub) {if (isNullOrEmpty(str) || isNullOrEmpty(sub)) {return 0;}int count = 0;int index = 0;while ((index = str.indexOf(sub, index)) != -1) {count++;index += sub.length();}return count;
}
- 判断字符串是否以指定前缀开头
public static boolean startsWith(String str, String prefix) {if (isNullOrEmpty(str) || isNullOrEmpty(prefix)) {return false;}return str.startsWith(prefix);
}
- 判断字符串是否以指定后缀结尾
public static boolean endsWith(String str, String suffix) {if (isNullOrEmpty(str) || isNullOrEmpty(suffix)) {return false;}return str.endsWith(suffix);
}
- 将字符串根据指定分隔符进行分割
public static String[] split(String str, String separator) {if (isNullOrEmpty(str)) {return new String[0];}return str.split(separator);
}
- 将字符串中的大小写进行转换
public static String toLowerCase(String str) {if (isNullOrEmpty(str)) {return str;}return str.toLowerCase();
}public static String toUpperCase(String str) {if (isNullOrEmpty(str)) {return str;}return str.toUpperCase();
}
- 判断两个字符串是否相等,忽略大小写
public static boolean equalsIgnoreCase(String str1, String str2) {if (isNullOrEmpty(str1) || isNullOrEmpty(str2)) {return false;}return str1.equalsIgnoreCase(str2);
}