将带下划线的字符串转换成大写(下划线后大写)的高效方法

版权声明:转载请注明作者及出处,否则将追究法律责任。 https://blog.csdn.net/q2158798/article/details/80531437

test_tb_kkk_llll  转换为    TestTbKkkLlll

原理:

1. 判断是否包含下划线

    (1) 包含:

        ① 按下划线将字符串切割成字符串数组

        ② 在循环里调用本方法(这个字符串肯定不包含下划线)(递归)

    (2) 不包含:

        ① 转换成字符数组

        ② 根据ASCII表将首字母变大写

ASCII表中的小写字母比大写大32,减去32即可,看下图即可

 

代码如下:


/**
	 * 方法说明 :将首字母和带 _ 后第一个字母 转换成大写
	 * 
	 * @return :String
	 * @author :HFanss
	 * @date :2018年5月31日下午9:52:19
	 */
	public static String upperTable(String str)
	{
		// 字符串缓冲区
		StringBuffer sbf = new StringBuffer();
		// 如果字符串包含 下划线
		if (str.contains("_"))
		{
			// 按下划线来切割字符串为数组
			String[] split = str.split("_");
			// 循环数组操作其中的字符串
			for (int i = 0, index = split.length; i < index; i++)
			{
				// 递归调用本方法
				String upperTable = upperTable(split[i]);
				// 添加到字符串缓冲区
				sbf.append(upperTable);
			}
		} else
		{// 字符串不包含下划线
			// 转换成字符数组
			char[] ch = str.toCharArray();
			// 判断首字母是否是字母
			if (ch[0] >= 'a' && ch[0] <= 'z')
			{
				// 利用ASCII码实现大写
				ch[0] = (char) (ch[0] - 32);
			}
			// 添加进字符串缓存区
			sbf.append(ch);
		}
		// 返回
		return sbf.toString();
	}

猜你喜欢

转载自blog.csdn.net/q2158798/article/details/80531437