Convert a name in camelCase to an underscored name in lower case. - Java java.lang

Java examples for java.lang:String Camel Case

Description

Convert a name in camelCase to an underscored name in lower case.

Demo Code


import static org.mynah.oblatum.util.Constants.UNDERLINE;

public class Main{
    public static void main(String[] argv) throws Exception{
        String name = "java2s.com";
        System.out.println(underscoreName(name));
    }/*from www .j a  va 2 s.  co  m*/
    /**
     * Convert a name in camelCase to an underscored name in lower case.
     * Any upper case letters are converted to lower case with a preceding underscore.
     *
     * @param name the string containing original name
     * @return the converted name
     */
    public static String underscoreName(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            result.append(name.substring(0, 1).toLowerCase());
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                String slc = s.toLowerCase();
                if (!s.equals(slc)) {
                    result.append(UNDERLINE).append(slc);
                } else {
                    result.append(s);
                }
            }
        }
        return result.toString();
    }
}

Related Tutorials