Java下划线转驼峰--小练习

2021/10/19 22:09:45

本文主要是介绍Java下划线转驼峰--小练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

static final char UNDER_LINE = '_';

public static void main(String[] args) {

  // 下划线转驼峰
  String source = "income_ratio";
  String target = toCase(source);
  System.out.println("target = " + target);
}

static String toCase(String source) {
	if (source == null || source.trim().isEmpty()) {
		return null;
	}
	StringBuilder target = new StringBuilder();
	char[] charSourceArray = source.toCharArray();
	char[] chartargeteArray1 = new char[charSourceArray.length];
	char[] chartargeteArray2 = chartargeteArray1.clone();
	for (int i = 0; i < charSourceArray.length; i++) {
    	// char值是否为数字
		if (Character.isDigit(charSourceArray[i])) {
			continue;
		}
        // char值是否为空格
		if (Character.isWhitespace(charSourceArray[i])) {
			continue;
		}
        // 如果是下划线,下划线后的字母转大写字母,否则都为小写字母
		chartargeteArray1[i] = UNDER_LINE == charSourceArray[i] ? Character.toUpperCase(charSourceArray[i + 1]) : Character.toLowerCase(charSourceArray[i]);
	}
	for (int i = 0; i < chartargeteArray1.length; i++) {
		if (i >= 1) {
        	// char值是否为大写字母
			if (Character.isUpperCase(chartargeteArray1[i - 1])) {
				continue;
			}
		}
		chartargeteArray2[i] = chartargeteArray1[i];
		target.append(chartargeteArray2[i]);
	}
	return target.toString();
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------
只是简单的小练习,未考虑到边界值问题
-----------------------------------------------------------------------------------------------------------------------------------------------------------
target = incomeRatio


这篇关于Java下划线转驼峰--小练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程