Convert aStringUnderscored into A_STRING_A. - Java java.lang

Java examples for java.lang:String Split

Description

Convert aStringUnderscored into A_STRING_A.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String camelCaseString = "java2s.com";
        System.out.println(camelCaseToUnderscore(camelCaseString));
    }/*from   www.  j  a  va 2 s . c om*/

    /**
     * Convert aStringUnderscored into A_STRING_A.
     * 
     * @param camelCaseString the string to convert
     * 
     * @return the underscored string
     */
    public static String camelCaseToUnderscore(final String camelCaseString) {

        StringBuilder sb = new StringBuilder();
        for (String camelPart : camelCaseString
                .split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
            if (sb.length() > 0) {
                sb.append("_");
            }
            sb.append(camelPart.toUpperCase());
        }
        return sb.toString();
    }
}

Related Tutorials