Java String Clean cleanStringForJavaName(String original)

Here you can find the source of cleanStringForJavaName(String original)

Description

clean String For Java Name

License

Creative Commons License

Declaration

public static String cleanStringForJavaName(String original) 

Method Source Code

//package com.java2s;
/*// w ww . jav a  2s  .  co m
 * This software is in the public domain under CC0 1.0 Universal plus a
 * Grant of Patent License.
 *
 * To the extent possible under law, the author(s) have dedicated all
 * copyright and related and neighboring rights to this software to the
 * public domain worldwide. This software is distributed without any
 * warranty.
 *
 * You should have received a copy of the CC0 Public Domain Dedication
 * along with this software (see the LICENSE.md file). If not, see
 * <http://creativecommons.org/publicdomain/zero/1.0/>.
 */

public class Main {
    public static String cleanStringForJavaName(String original) {
        if (original == null || original.isEmpty())
            return original;
        char[] origChars = original.toCharArray();
        char[] cleanChars = new char[origChars.length];
        boolean isIdentifierStart = true;
        for (int i = 0; i < origChars.length; i++) {
            char curChar = origChars[i];
            // remove dots too, get down to simple class name to work best with Groovy class compiling and loading
            // if (curChar == '.') { cleanChars[i] = '.'; isIdentifierStart = true; continue; }
            // also don't allow $ as groovy blows up on it with class compile/load
            if (curChar != '$' && (isIdentifierStart ? Character.isJavaIdentifierStart(curChar)
                    : Character.isJavaIdentifierPart(curChar))) {
                cleanChars[i] = curChar;
            } else {
                cleanChars[i] = '_';
            }
            isIdentifierStart = false;
        }
        // logger.warn("cleaned " + original + " to " + new String(cleanChars));
        return new String(cleanChars);
    }
}

Related

  1. cleanStringArrayChar(String value)
  2. cleanStringByLikeWithHSQL(String input)
  3. cleanStringCamelCase(String in)
  4. cleanStringForFilename(String originalString)
  5. cleanStringForFilePath(final String dirty)
  6. cleanStringFromWhitespaces(String text)
  7. cleanText(final String input)
  8. cleanText(String s)
  9. cleanText(String s)