Java String Camel Case to Snake Case camelToSnake(String camel, boolean upper)

Here you can find the source of camelToSnake(String camel, boolean upper)

Description

Converts camel case string (lower or upper/Pascal) to snake case, for example 'helloWorld' or 'HelloWorld' -> 'hello_world'.

License

Open Source License

Parameter

Parameter Description
camel Input string.
upper True if result snake cased string should be upper cased like 'HELLO_WORLD'.

Declaration

public static String camelToSnake(String camel, boolean upper) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   ww w.  j  a v  a2 s.com
     * Converts camel case string (lower or upper/Pascal) to snake case,
     * for example 'helloWorld' or 'HelloWorld' -> 'hello_world'.
     *
     * @param camel Input string.
     * @param upper True if result snake cased string should be upper cased like 'HELLO_WORLD'.
     */
    public static String camelToSnake(String camel, boolean upper) {
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : camel.toCharArray()) {
            char nc = upper ? Character.toUpperCase(c) : Character.toLowerCase(c);
            if (Character.isUpperCase(c)) {
                stringBuilder.append('_').append(nc);
            } else {
                stringBuilder.append(nc);
            }
        }
        return stringBuilder.toString();
    }
}

Related

  1. camelToSnake(final String camelStr)
  2. camelToSnake(String value)
  3. camelToSnakeCase(final String camelCase)
  4. camelToSnakeCase(String camelcase)
  5. camelToSnakeCase(String string)