Here you can find the source of sanitizeName(String name)
Parameter | Description |
---|---|
name | A string with spaces and other characters that cannot be in a Java name. |
public static String sanitizeName(String name)
//package com.java2s; //License from project: Open Source License public class Main { /** Sanitize a String so that it can be used as a Java identifier. * Section 3.8 of the Java language spec says: * <blockquote>/*from w w w. j a v a 2s. c o m*/ * "An identifier is an unlimited-length sequence of Java letters * and Java digits, the first of which must be a Java letter. An * identifier cannot have the same spelling (Unicode character * sequence) as a keyword (3.9), boolean literal (3.10.3), or * the null literal (3.10.7)." * </blockquote> * Java characters are A-Z, a-z, $ and _. * <p> Characters that are not permitted in a Java identifier are changed * to underscores. * This method does not check that the returned string is a * keyword or literal. * Note that two different strings can sanitize to the same * string. * This method is commonly used during code generation to map the * name of a ptolemy object to a valid identifier name. * @param name A string with spaces and other characters that * cannot be in a Java name. * @return A String that follows the Java identifier rules. */ public static String sanitizeName(String name) { char[] nameArray = name.toCharArray(); for (int i = 0; i < nameArray.length; i++) { if (!Character.isJavaIdentifierPart(nameArray[i])) { nameArray[i] = '_'; } } if (nameArray.length == 0) { return ""; } else { if (!Character.isJavaIdentifierStart(nameArray[0])) { return "_" + new String(nameArray); } else { return new String(nameArray); } } } }