Java String Underscore toUnderscored(String name)

Here you can find the source of toUnderscored(String name)

Description

to Underscored

License

Open Source License

Declaration

public static String toUnderscored(String name) 

Method Source Code

//package com.java2s;

public class Main {
    public static String toUnderscored(String name) {
        return toEnglish(name).replaceAll(" ", "_").toLowerCase();
    }/*from   w ww.j  ava 2s  .c o  m*/

    public static String toEnglish(String name) {

        // We don't need underscores as name separators
        name.replaceAll("_", " ");

        // Detect camel case and split it
        //if(!name.matches("^[A-Z ]+$")) {
        name = splitCamelCase(name);
        //}

        return name;
    }

    private static String splitCamelCase(String name) {
        if (name == null || name.length() == 0) {
            return "";
        }

        StringBuffer result = new StringBuffer();

        char prevChar = ' ';

        // Change underscore to space, insert space before capitals
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (c == '_') {
                result.append(' ');
            } else if (prevChar == ' ' || prevChar == '_') {
                result.append(Character.toUpperCase(c));
            } else if (Character.isUpperCase(c) && !Character.isUpperCase(prevChar)) {
                // Insert space before start of word if camel case
                result.append(' ');
                result.append(Character.toUpperCase(c));
            } else {
                result.append(c);
            }

            prevChar = c;
        }

        return result.toString();
    }
}

Related

  1. toUnderscore(String v)
  2. toUnderscoreCase(final String s)
  3. toUnderscoreCase(String name)
  4. toUnderScoreCase(String s)
  5. toUnderScoreCase(String s)
  6. toUnderscoredLowercase(String text)
  7. toUnderscoreName(String name)
  8. toUnderscores(String s)
  9. toUnderscoreSeparated(String name)