Java String Underscore underscore(String phase)

Here you can find the source of underscore(String phase)

Description

underscore is the reverse of camelize method.

License

LGPL

Parameter

Parameter Description
phase the original string

Return

an underscored string

Declaration

public static String underscore(String phase) 

Method Source Code

//package com.java2s;
/*//w w  w  .java2 s.  c o m
 *   This software is distributed under the terms of the FSF
 *   Gnu Lesser General Public License (see lgpl.txt).
 *
 *   This program is distributed WITHOUT ANY WARRANTY. See the
 *   GNU General Public License for more details.
 */

public class Main {
    private static String A2Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static String a2z = "abcdefghijklmnopqrstuvwxyz";

    /**
     * <tt>underscore</tt> is the reverse of <tt>camelize</tt> method.
     *
     * <pre>
     * Examples:
     *   underscore("Hello world")  ==> "hello world"
     *   underscore("ActiveRecord") ==> "active_record"
     *   underscore("The RedCross") ==> "the red_cross"
     *   underscore("ABCD")         ==> "abcd"
     * </pre>
     *
     * @param phase             the original string
     * @return an underscored string
     */
    public static String underscore(String phase) {
        if (phase == null || "".equals(phase))
            return phase;

        phase = phase.replace('-', '_');
        StringBuilder sb = new StringBuilder();
        int total = phase.length();
        for (int i = 0; i < total; i++) {
            char c = phase.charAt(i);
            if (i == 0) {
                if (isInA2Z(c)) {
                    sb.append(("" + c).toLowerCase());
                } else {
                    sb.append(c);
                }
            } else {
                if (isInA2Z(c)) {
                    if (isIna2z(phase.charAt(i - 1))) {
                        sb.append(("_" + c).toLowerCase());
                    } else {
                        sb.append(("" + c).toLowerCase());
                    }
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    private static boolean isInA2Z(char c) {
        return (A2Z.indexOf(c) != -1) ? true : false;
    }

    private static boolean isIna2z(char c) {
        return (a2z.indexOf(c) != -1) ? true : false;
    }
}

Related

  1. toUnderscoreSeparated(String name)
  2. underscore(final String s, final Locale locale)
  3. underscore(String camel)
  4. underscore(String camelCaseWord)
  5. underscore(String field)
  6. underscore(String str)
  7. underscore(String word)
  8. underscoreAllWhitespace(String str)
  9. underscoreAndLowercase(String s)