下划线转驼峰命名

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程

public class Test {
    
    
	/** 下划线 */
    private static final char SEPARATOR = '_';
	  /**
     * 下划线转驼峰命名
     */
    public static String toUnderScoreCase(String str)
    {
    
    
        if (str == null)
        {
    
    
            return null;
        }
        StringBuilder sb = new StringBuilder();
        // 前置字符是否大写
        boolean preCharIsUpperCase = true;
        // 当前字符是否大写
        boolean curreCharIsUpperCase = true;
        // 下一字符是否大写
        boolean nexteCharIsUpperCase = true;
        for (int i = 0; i < str.length(); i++)
        {
    
    
            char c = str.charAt(i);
            if (i > 0)
            {
    
    
                preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
            }
            else
            {
    
    
                preCharIsUpperCase = false;
            }

            curreCharIsUpperCase = Character.isUpperCase(c);

            if (i < (str.length() - 1))
            {
    
    
                nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
            }

            if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
            {
    
    
                sb.append(SEPARATOR);
            }
            else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
            {
    
    
                sb.append(SEPARATOR);
            }
            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }

	public static void main(String[] args) {
    
    
		String str = "userName"; // 输出user_name
		System.out.println(toUnderScoreCase(str));
	}

}

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/113113136
今日推荐