Java ID Value Create toIdentifier(String str)

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

Description

Given a string, returns a proper C identifier.

License

Open Source License

Parameter

Parameter Description
name a parameter

Declaration

public static String toIdentifier(String str) 

Method Source Code

//package com.java2s;
/*  Copyright (C) 2009 Mobile Sorcery AB
    // w  ww .  j  ava  2  s  .  c o  m
This program is free software; you can redistribute it and/or modify it
under the terms of the Eclipse Public License v1.0.
    
This program 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 Eclipse Public License v1.0 for
more details.
    
You should have received a copy of the Eclipse Public License v1.0 along
with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html
*/

public class Main {
    /**
     * Given a string, returns a proper C identifier.
     * @param name
     * @return
     */
    public static String toIdentifier(String str) {
        // C = Java identifiers :)
        StringBuffer buf = new StringBuffer();
        if (!str.isEmpty()) {
            char first = str.charAt(0);
            if (Character.isJavaIdentifierPart(first) && !Character.isJavaIdentifierStart(first)) {
                buf.append("_");
            }
            for (int i = 0; i < str.length(); i++) {
                char ch = str.charAt(i);
                if (Character.isJavaIdentifierPart(ch)) {
                    buf.append(Character.toUpperCase(ch));
                } else {
                    buf.append("_");
                }
            }
        }
        return buf.toString();
    }

    public static boolean isEmpty(String text) {
        return text == null || text.isEmpty();
    }
}

Related

  1. toId(String text)
  2. toIdableName(String xpath)
  3. toIdentifier(String input)
  4. toIdentifier(String name)
  5. toIdentifier(String name, StringBuffer fieldName)
  6. toIdentifier(String text)
  7. toIdentifierString(long val)
  8. toIdentityEncodedString(byte[] data)
  9. toIdentityHashCodeInteger(Object value)