Java ID Value Create toIdentityVariableName(String varName)

Here you can find the source of toIdentityVariableName(String varName)

Description

translate a string to a valid identity variable name

License

LGPL

Parameter

Parameter Description
varName variable name template to translate

Return

translated variable name

Declaration

public static String toIdentityVariableName(String varName) 

Method Source Code

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

public class Main {
    /**//from  www. ja v  a 2  s . c o m
     * translate a string to a valid identity variable name
     * @param varName variable name template to translate
     * @return translated variable name
     */
    public static String toIdentityVariableName(String varName) {
        char[] chars = varName.toCharArray();
        long changes = 0;

        StringBuilder rtn = new StringBuilder(chars.length + 2);
        rtn.append("CF");

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
                rtn.append(c);
            else {
                rtn.append('_');
                changes += (c * (i + 1));
            }
        }

        return rtn.append(changes).toString();
    }

    /**
     * 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);
    }

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

Related

  1. toIdentifier(String str)
  2. toIdentifier(String text)
  3. toIdentifierString(long val)
  4. toIdentityEncodedString(byte[] data)
  5. toIdentityHashCodeInteger(Object value)
  6. toIdSet(boolean includeAlphaCharacters, String nonAlphaCharacters)
  7. toIDString(final byte[] id)