Java String Camel Case to Underscore camelToUnderLineString(String str)

Here you can find the source of camelToUnderLineString(String str)

Description

null => "" " " => "" "abc" => "abc" "aBc" => "a_bc" "helloWord" => "hello_word" "hi hao are you" => "hi hao are you" "helloWord_iAmHsl" => "hello_word_i_am_hsl"

License

Apache License

Declaration

public static String camelToUnderLineString(String str) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static final String EMPTY = "";

    /**//from  ww w . ja  v a  2 s  .c o  m
     * null      =>      ""
     * "   "   =>      ""
     * "abc"   =>      "abc"
     * "aBc"   =>      "a_bc"
     * "helloWord"   =>   "hello_word"
     * "hi hao are   you"   => "hi hao are   you"
     * "helloWord_iAmHsl"   =>   "hello_word_i_am_hsl"
     * @return
     */
    public static String camelToUnderLineString(String str) {
        return camelToFixedString(str, "_");
    }

    public static String camelToFixedString(String str, String fixed) {
        str = trimToEmpty(str);
        if (isEmpty(str)) {
            return str;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); ++i) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i != 0) {
                    sb.append(fixed);
                }
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String trimToEmpty(String input) {
        if (input == null) {
            return EMPTY;
        }
        return input.trim();
    }

    public static boolean isEmpty(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        return false;
    }
}

Related

  1. camelCaseToUnderscores(String camel)
  2. camelCaseToUnderScoreUpperCase(String camelCase)
  3. camelToUnder(String value)
  4. camelToUnderline(String param)
  5. camelToUnderlinedName(String name)
  6. camelToUnderscore(String value)