Home > other >  Java convert camel case to underscore?
Java convert camel case to underscore?

Time:12-01

What method can I use for reach this:

If my String is: mailSPA: I want mail_spa

If my String is: mailSPAOther -> mail_spaother

I tried this method:

public static String camelToUnderscore(String input) {
        if (input == null) {
            return "";
        }
        String regex = "([A-Z])";
        String replacement = "_$1";
        String result = input.replaceAll(regex, replacement).toLowerCase();
        if (result.startsWith("_"))
            return result.substring(1);
        return result;
    }

but it transform my string mailSPA to mail_s_p_a

CodePudding user response:

Try this one;

public static String camelToUnderscore(String input) {
  if (input == null) {
    return "";
  }
  String regex = "([a-z])([A-Z])";
  String replacement = "$1_$2";
  String result = input.replaceAll(regex, replacement).toLowerCase();
  if (result.startsWith("_"))
    return result.substring(1);
  return result;
}

CodePudding user response:

A simple non-regex solution via Iterating the String once would be:

public static String camelToUnderscore(final String input) {
    if (input == null) {
        return "";
    }
    final StringBuilder sb = new StringBuilder();
    final char[] charArray = input.toCharArray();
    for (int i = 0; i < charArray.length; i  ) {
        final char currentChar = charArray[i];
        if (i > 1 && Character.isUpperCase(currentChar) && Character.isLowerCase(charArray[i-1])) {
            sb.append("_" Character.toLowerCase(currentChar));
        } else {
            sb.append(Character.toLowerCase(currentChar));
        }
    }
    return sb.toString();
}
  • Related