Java字符串工具类案例怎么开发

wen java案例 23

本文目录导读:

Java字符串工具类案例怎么开发

  1. 基础工具类结构
  2. 常用判空方法
  3. 字符串转换方法
  4. 字符串截取和填充
  5. 字符串校验方法
  6. 字符串处理高级方法
  7. 测试类示例
  8. 使用示例

我来详细介绍如何开发一个Java字符串工具类(StringUtils)的案例。

基础工具类结构

package com.example.util;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 字符串工具类
 */
public class StringUtils {
    // 私有构造函数,防止实例化
    private StringUtils() {
        throw new UnsupportedOperationException("工具类不能实例化");
    }
}

常用判空方法

/**
 * 判断字符串是否为空
 */
public static boolean isEmpty(String str) {
    return str == null || str.trim().length() == 0;
}
/**
 * 判断字符串是否不为空
 */
public static boolean isNotEmpty(String str) {
    return !isEmpty(str);
}
/**
 * 判断字符串是否为空(包括空白字符)
 */
public static boolean isBlank(String str) {
    return str == null || str.trim().isEmpty();
}
/**
 * 判断字符串是否不为空
 */
public static boolean isNotBlank(String str) {
    return !isBlank(str);
}

字符串转换方法

/**
 * 首字母大写
 */
public static String capitalize(String str) {
    if (isEmpty(str)) {
        return str;
    }
    return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
/**
 * 首字母小写
 */
public static String uncapitalize(String str) {
    if (isEmpty(str)) {
        return str;
    }
    return Character.toLowerCase(str.charAt(0)) + str.substring(1);
}
/**
 * 转换为驼峰命名(下划线转驼峰)
 */
public static String toCamelCase(String str) {
    if (isEmpty(str)) {
        return str;
    }
    StringBuilder result = new StringBuilder();
    boolean nextUpperCase = false;
    for (char ch : str.toCharArray()) {
        if (ch == '_') {
            nextUpperCase = true;
        } else if (nextUpperCase) {
            result.append(Character.toUpperCase(ch));
            nextUpperCase = false;
        } else {
            result.append(Character.toLowerCase(ch));
        }
    }
    return result.toString();
}
/**
 * 转换为下划线命名(驼峰转下划线)
 */
public static String toUnderlineCase(String str) {
    if (isEmpty(str)) {
        return str;
    }
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (Character.isUpperCase(ch)) {
            if (i > 0) {
                result.append('_');
            }
            result.append(Character.toLowerCase(ch));
        } else {
            result.append(ch);
        }
    }
    return result.toString();
}

字符串截取和填充

/**
 * 截取字符串前n个字符
 */
public static String truncate(String str, int maxWidth) {
    if (str == null) {
        return null;
    }
    if (maxWidth < 0) {
        return str;
    }
    if (str.length() <= maxWidth) {
        return str;
    }
    return str.substring(0, maxWidth);
}
/**
 * 左填充
 */
public static String leftPad(String str, int size, char padChar) {
    if (str == null) {
        return null;
    }
    int pads = size - str.length();
    if (pads <= 0) {
        return str;
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < pads; i++) {
        sb.append(padChar);
    }
    sb.append(str);
    return sb.toString();
}
/**
 * 右填充
 */
public static String rightPad(String str, int size, char padChar) {
    if (str == null) {
        return null;
    }
    int pads = size - str.length();
    if (pads <= 0) {
        return str;
    }
    StringBuilder sb = new StringBuilder(str);
    for (int i = 0; i < pads; i++) {
        sb.append(padChar);
    }
    return sb.toString();
}

字符串校验方法

/**
 * 是否为数字
 */
public static boolean isNumeric(String str) {
    if (isEmpty(str)) {
        return false;
    }
    return str.matches("-?\\d+(\\.\\d+)?");
}
/**
 * 是否为整数
 */
public static boolean isInteger(String str) {
    if (isEmpty(str)) {
        return false;
    }
    try {
        Integer.parseInt(str.trim());
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
/**
 * 是否为有效的邮箱地址
 */
public static boolean isValidEmail(String email) {
    if (isEmpty(email)) {
        return false;
    }
    String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
    Pattern pattern = Pattern.compile(emailRegex);
    return pattern.matcher(email).matches();
}
/**
 * 是否为有效的手机号(中国大陆)
 */
public static boolean isValidMobile(String mobile) {
    if (isEmpty(mobile)) {
        return false;
    }
    String mobileRegex = "^1[3-9]\\d{9}$";
    Pattern pattern = Pattern.compile(mobileRegex);
    return pattern.matcher(mobile).matches();
}

字符串处理高级方法

/**
 * 去除所有空格
 */
public static String removeAllSpaces(String str) {
    if (isEmpty(str)) {
        return str;
    }
    return str.replaceAll("\\s+", "");
}
/**
 * 去除指定字符
 */
public static String removeChar(String str, char removeChar) {
    if (isEmpty(str)) {
        return str;
    }
    StringBuilder sb = new StringBuilder();
    for (char ch : str.toCharArray()) {
        if (ch != removeChar) {
            sb.append(ch);
        }
    }
    return sb.toString();
}
/**
 * 字符串反转
 */
public static String reverse(String str) {
    if (isEmpty(str)) {
        return str;
    }
    return new StringBuilder(str).reverse().toString();
}
/**
 * 重复字符串
 */
public static String repeat(String str, int count) {
    if (str == null || count <= 0) {
        return "";
    }
    StringBuilder sb = new StringBuilder(str.length() * count);
    for (int i = 0; i < count; i++) {
        sb.append(str);
    }
    return sb.toString();
}
/**
 * 统计子字符串出现次数
 */
public static int countMatches(String str, String sub) {
    if (isEmpty(str) || isEmpty(sub)) {
        return 0;
    }
    int count = 0;
    int idx = 0;
    while ((idx = str.indexOf(sub, idx)) != -1) {
        count++;
        idx += sub.length();
    }
    return count;
}
/**
 * 隐藏敏感信息(如手机号、邮箱)
 */
public static String maskInfo(String str, int start, int end, char maskChar) {
    if (isEmpty(str)) {
        return str;
    }
    if (start < 0 || end > str.length() || start >= end) {
        return str;
    }
    StringBuilder sb = new StringBuilder(str);
    for (int i = start; i < end; i++) {
        sb.setCharAt(i, maskChar);
    }
    return sb.toString();
}

测试类示例

package com.example.test;
import com.example.util.StringUtils;
public class StringUtilsTest {
    public static void main(String[] args) {
        // 测试判空方法
        System.out.println("isEmpty测试:");
        System.out.println(StringUtils.isEmpty(null));           // true
        System.out.println(StringUtils.isEmpty(""));             // true
        System.out.println(StringUtils.isEmpty("  "));           // true
        System.out.println(StringUtils.isEmpty("hello"));        // false
        System.out.println("\nisBlank测试:");
        System.out.println(StringUtils.isBlank("  "));           // true
        System.out.println(StringUtils.isBlank("\t\n"));         // true
        // 测试驼峰转换
        System.out.println("\n驼峰转换测试:");
        System.out.println(StringUtils.toCamelCase("hello_world"));  // helloWorld
        System.out.println(StringUtils.toUnderlineCase("helloWorld")); // hello_world
        // 测试填充
        System.out.println("\n填充测试:");
        System.out.println(StringUtils.leftPad("5", 3, '0'));   // 005
        System.out.println(StringUtils.rightPad("5", 3, '0'));  // 500
        // 测试校验
        System.out.println("\n校验测试:");
        System.out.println(StringUtils.isNumeric("123.45"));    // true
        System.out.println(StringUtils.isValidEmail("test@example.com")); // true
        System.out.println(StringUtils.isValidMobile("13800138000"));     // true
        // 测试处理
        System.out.println("\n处理测试:");
        System.out.println(StringUtils.reverse("Hello"));       // olleH
        System.out.println(StringUtils.repeat("abc", 3));       // abcabcabc
        System.out.println(StringUtils.countMatches("hello hello", "hello")); // 2
        // 测试信息隐藏
        System.out.println("\n信息隐藏测试:");
        String phone = "13812345678";
        System.out.println(StringUtils.maskInfo(phone, 3, 7, '*')); // 138****5678
    }
}

使用示例

// 在实际项目中使用
public class UserService {
    public boolean createUser(String name, String email, String phone) {
        // 参数校验
        if (StringUtils.isEmpty(name)) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (!StringUtils.isValidEmail(email)) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }
        if (!StringUtils.isValidMobile(phone)) {
            throw new IllegalArgumentException("手机号格式不正确");
        }
        // 格式化数据
        String userName = StringUtils.capitalize(name.toLowerCase());
        // 记录日志(隐藏敏感信息)
        String safePhone = StringUtils.maskInfo(phone, 3, 7, '*');
        System.out.println("创建用户:" + userName + ", 手机:" + safePhone);
        return true;
    }
}

这个工具类包含了日常开发中常用的字符串处理功能,你可以根据项目需求进行扩展或修改,建议使用单元测试框架(如JUnit)来编写更完善的测试。

抱歉,评论功能暂时关闭!