0
点赞
收藏
分享

微信扫一扫

TCP协议-TCP知识点总结,巩固你的网路底层基础!

cwq聖泉寒江2020 2023-12-04 阅读 46

Java常用的字符串工具方法有很多,以下是一些常见的封装:

  1. 判断字符串是否为空或null
public static boolean isNullOrEmpty(String str) {
    return str == null || str.trim().isEmpty();
}

  1. 判断字符串是否为数字
public static boolean isNumeric(String str) {
    if (isNullOrEmpty(str)) {
        return false;
    }
    try {
        Double.parseDouble(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

  1. 去除字符串中的空格
public static String trim(String str) {
    if (isNullOrEmpty(str)) {
        return str;
    }
    return str.trim();
}

  1. 拼接字符串
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();
}

  1. 搜索指定字符串在原字符串中出现的次数
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;
}

  1. 判断字符串是否以指定前缀开头
public static boolean startsWith(String str, String prefix) {
    if (isNullOrEmpty(str) || isNullOrEmpty(prefix)) {
        return false;
    }
    return str.startsWith(prefix);
}

  1. 判断字符串是否以指定后缀结尾
public static boolean endsWith(String str, String suffix) {
    if (isNullOrEmpty(str) || isNullOrEmpty(suffix)) {
        return false;
    }
    return str.endsWith(suffix);
}

  1. 将字符串根据指定分隔符进行分割
public static String[] split(String str, String separator) {
    if (isNullOrEmpty(str)) {
        return new String[0];
    }
    return str.split(separator);
}

  1. 将字符串中的大小写进行转换
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();
}

  1. 判断两个字符串是否相等,忽略大小写
public static boolean equalsIgnoreCase(String str1, String str2) {
    if (isNullOrEmpty(str1) || isNullOrEmpty(str2)) {
        return false;
    }
    return str1.equalsIgnoreCase(str2);
}
举报

相关推荐

0 条评论