본문 바로가기

Programming/Java

[JAVA]camel 케이스 문자열을 snake 케이스 문자열로 변환

protected static String camelToSnake(String str)
    {
        // Empty String
        String result = "";

        // Append first character(in lower case)
        // to result string
        char c = str.charAt(0);
        result = result + Character.toLowerCase(c);

        // Tarverse the string from
        // ist index to last index
        for (int i = 1; i < str.length(); i++) {

            char ch = str.charAt(i);

            // Check if the character is upper case
            // then append '_' and such character
            // (in lower case) to result string
            if (Character.isUpperCase(ch)) {
                result = result + '_';
                result = result
                        + Character.toLowerCase(ch);
            }

            // If the character is lower case then
            // add such character into result string
            else {
                result = result + ch;
            }
        }

        // return the result
        return result;
    }

CAMEL CASE : 첫글자는 소문자, 이어지는 음절에서는 첫글자를 각각 대문자로 표기하는 방식

  ex) resultColumn 

SNAKE CASE : 전부 소문자로 하고 음절마다 '_'로 구분하여 표기하는 방식 

 ex) RESULT_COLUMN

728x90