Java Java String Format toJavaIdentifier(String name)

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

Description

to Java Identifier

License

Open Source License

Declaration

public static final String toJavaIdentifier(String name) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011, 2012 Red Hat, Inc. 
 * All rights reserved. //from w  w  w .j  a  va  2  s  .  c  om
 * This program is made available under the terms of the 
 * Eclipse Public License v1.0 which accompanies this distribution, 
 * and is available at http://www.eclipse.org/legal/epl-v10.html 
 *
 * Contributors: 
 * Red Hat, Inc. - initial API and implementation 
 *******************************************************************************/

public class Main {
    public static final String toJavaIdentifier(String name) {
        if (name == null || name.isEmpty())
            return "_"; //$NON-NLS-1$

        StringBuffer ncname = new StringBuffer();
        int nameLength = name.length();

        // Check first character
        char c = name.charAt(0);

        if (Character.isJavaIdentifierStart(c))
            ncname.append(c);
        else
            ncname.append('_');
        // Check the rest of the characters
        for (int i = 1; i < nameLength; i++) {
            c = name.charAt(i);
            if (!Character.isJavaIdentifierPart(c)) {
                c = '_';
            }
            ncname.append(c);
        }
        return ncname.toString();
    }
}

Related

  1. toJavadocComment(String comment)
  2. toJavaEnum(String inStr)
  3. toJavaHex(byte in[], int len)
  4. toJavaHexCharString(final char chr)
  5. toJavaIdentifier(String name)
  6. toJavaIdentifier(String nodeName, boolean boundary)
  7. toJavaIdentifier(String s)
  8. toJavaIdentifier(String source)
  9. toJavaIdentifier(String str)