Java Class Name Create toClassName(String str)

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

Description

translate a string to a valid classname string

License

LGPL

Parameter

Parameter Description
str string to translate

Return

translated String

Declaration

public static String toClassName(String str) 

Method Source Code

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

public class Main {
    /**/*from   www  .  j  a v a  2 s  . com*/
     * translate a string to a valid classname string
     * @param str string to translate
     * @return translated String
     */
    public static String toClassName(String str) {
        StringBuilder rtn = new StringBuilder();
        String[] arr = str.split("[\\\\|//]");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].length() == 0)
                continue;
            if (rtn.length() != 0)
                rtn.append('.');
            char[] chars = arr[i].toCharArray();
            long changes = 0;
            for (int y = 0; y < chars.length; y++) {
                char c = chars[y];
                if (y == 0 && (c >= '0' && c <= '9'))
                    rtn.append("_" + c);
                else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
                    rtn.append(c);
                else {
                    rtn.append('_');
                    changes += (c * (i + 1));
                }
            }
            if (changes > 0)
                rtn.append(changes);
        }
        return rtn.toString();
    }

    public static int length(String str) {
        if (str == null)
            return 0;
        return str.length();
    }

    /**
     * returns string, if given string is null or lengt 0 return default value
     * @param value
     * @param defaultValue
     * @return value or default value
     */
    public static String toString(String value, String defaultValue) {
        return value == null || value.length() == 0 ? defaultValue : value;
    }

    /**
     * returns string, if given string is null or lengt 0 return default value
     * @param value
     * @param defaultValue
     * @return value or default value
     */
    public static String toString(Object value, String defaultValue) {
        if (value == null)
            return defaultValue;
        return toString(value.toString(), defaultValue);
    }
}

Related

  1. toClassName(String className)
  2. toClassName(String fileName)
  3. toClassName(String fileName)
  4. toClassName(String internalName)
  5. toClassName(String resourceName)
  6. toClassNames(Class... classes)