下划线转驼峰式工具类

近期在写一个迷你型的mybaits框架,涉及到数据库字段映射到Java实体类时遇到的需要将下换线转命名成驼峰命名。

一般有两种实现方式:

  • 操作字节数组,性能较高,可读性较差
  • 使用String类提供的方法实现,性能较低

1.操作字节数组实现下划线转驼峰

package com.yanling.mybatis.util;

/**
 * @description: 下划线转换驼峰工具类
 * @author: yanling
 * @time: 2021/1/2
 */
public class ToHumpUtil {
	/**
	 * 下划线对应的ASCII
	 */
	private static final byte ASCII_UNDER_LINE = 95;

	/**
	 * 小写字母a的ASCII
	 */
	private static final byte ASCII_a = 97;

	/**
	 * 大写字母A的ASCII
	 */
	private static final byte ASCII_A = 65;

	/**
	 * 小写字母z的ASCII
	 */
	private static final byte ASCII_z = 122;

	/**
	 * 字母a和A的ASCII差距(a-A的值)
	 */
	private static final byte ASCII_a_A = ASCII_a - ASCII_A;

	public static String toHump(String column) {
		byte[] bytes = changeIdx(column);
		bytes = removeUnderLine(bytes);
		return new String(bytes);
	}

	/**
	 * 交换下划线和其后面字符的下标
	 * 将column从下划线命名方式转换成驼峰命名方式
	 * 0. 找到‘_’符号的ASCII码(95)对应的下标
	 * 1. 将下划线的下标的下一个元素转换为大写字段(如果是小写字母的话)并放到下划线对应的下标
	 * 2. 将下划线下标的下一个元素设置为下划线
	 * 3. 返回数组
	 *
	 * @param column 字段名称
	 */
	private static byte[] changeIdx(String column) {
		byte[] bytes = column.getBytes();
		for (int i = 0; i < bytes.length; i++) {
			if (bytes[i] == ASCII_UNDER_LINE) {
				if (i < bytes.length - 1) {
					bytes[i] = toUpper(bytes[i + 1]);
					bytes[i + 1] = ASCII_UNDER_LINE;
					i++;
				}
			}
		}
		return bytes;
	}

	/**
	 * 将参数b转换为大写字母,小写字母ASCII范围(97~122)
	 * 0. 判断参数是否为小写字母
	 * 1. 将小写字母转换为大写字母(减去32)
	 */
	private static byte toUpper(byte b) {
		if (b >= ASCII_a && b <= ASCII_z) {
			return (byte) (b - ASCII_a_A);
		}
		return b;
	}

	/**
	 * 去除所有下划线
	 * 0. 新创建一个数组
	 * 1. 将所有非下划线字符都放入新数组中
	 *
	 * @param bytes 原始数组
	 * @return 处理后的字节数组
	 */
	private static byte[] removeUnderLine(byte[] bytes) {
		// 存放非下划线字符的数量
		int count = 0;
		for (byte b : bytes) {
			if (b == ASCII_UNDER_LINE) {
				continue;
			}
			count++;
		}
		byte[] nBytes = new byte[count];
		count = 0;
		for (byte b : bytes) {
			if (b == ASCII_UNDER_LINE) {
				continue;
			}
			nBytes[count] = b;
			count++;
		}
		return nBytes;
	}

}

2.通过使用String自带的方法实现下划线转驼峰

/**
 * 下划线转换驼峰工具类,通过String来实现
 */
public class ToHumpUtilByString {
    /**
     * 将下划线命名转换驼峰式命名
     * 0. 先将字符串以下划线字符进行分割
     * 1. 从第1个下标开始将字符串的首字母转换成大写
     * 2. 拼接所有字符串
     * 3. 返回新的字符串
     *
     * @param column 字段名称
     * @return 新的字段名称
     */
    public static String toHump(String column) {
        String[] s = column.split("_");
        if (s.length == 0) {
            return column;
        }
        String res = s[0];
        for (int i = 1; i < s.length; i++) {
            res += s[i].substring(0, 1).toUpperCase() + s[i].substring(1);
        }
        return res;
    }
}

3.测试结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值