Back/Spring Java

CamelCase, SnakeCase Convert Function

밍꿔 2020. 1. 14. 18:09


반응형

 

Camelcase -> Snakecase 변환

public static String convertCamelToSnake(String str){
    String regex = "([a-z])([A-Z])";
    String replacement = "$1_$2";
    String value = "";
    value = str.replaceAll(regex, replacement).toLowerCase();
    return value;
}

 

 

Snakecase -> Camelcase  변환

public static String convertSnakeToCamel(String str) {

    if (str.indexOf('_') < 0 && Character.isLowerCase(str.charAt(0))) {
        return str;
    }
	
    StringBuilder result = new StringBuilder();
    boolean nextUpper = false;
    int len = str.length();

    for (int i = 0; i < len; i++) {
	    char currentChar = str.charAt(i);	
        if (currentChar == '_') {
            nextUpper = true;
	    } else {	
            if (nextUpper) {
                result.append(Character.toUpperCase(currentChar));
                nextUpper = false;
            } else {
                result.append(Character.toLowerCase(currentChar));
            }
        }
    }
    return result.toString();
}

 

 

 

반응형