Java ID Value Create toIdentifier(String input)

Here you can find the source of toIdentifier(String input)

Description

Modifies all characters which are not valid in an identifier; leading and trailing blanks are removed.

License

Open Source License

Parameter

Parameter Description
input Input

Return

Modified input

Declaration

public static String toIdentifier(String input) 

Method Source Code

//package com.java2s;
/*//from   ww  w . j a va  2  s. c  o  m
 * NBCndUnit - C/C++ unit tests for NetBeans.
 * Copyright (C) 2015  offa
 * 
 * This file is part of NBCndUnit.
 *
 * NBCndUnit is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NBCndUnit is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NBCndUnit.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Modifies all characters which are not valid in an identifier; leading
     * and trailing blanks are removed.
     * 
     * @param input     Input
     * @return          Modified input
     */
    public static String toIdentifier(String input) {
        final String ti = input.trim();

        if (ti.isEmpty() == true) {
            return ti;
        }

        final StringBuilder sb = new StringBuilder(ti);
        char c = sb.charAt(0);

        if (Character.isJavaIdentifierStart(c) == false || c == '$') {
            sb.setCharAt(0, '_');
        }

        for (int i = 1; i < sb.length(); i++) {
            c = sb.charAt(i);

            if (Character.isJavaIdentifierPart(c) == false || c == '$') {
                sb.setCharAt(i, '_');
            }
        }

        return sb.toString();
    }
}

Related

  1. generateUniqueString(int maxLength)
  2. toId(String id)
  3. toId(String name)
  4. toId(String text)
  5. toIdableName(String xpath)
  6. toIdentifier(String name)
  7. toIdentifier(String name, StringBuffer fieldName)
  8. toIdentifier(String str)
  9. toIdentifier(String text)