camel Case to Underscore - Java java.lang

Java examples for java.lang:String Camel Case

Description

camel Case to Underscore

Demo Code


//package com.java2s;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) throws Exception {
        String param = "java2s.com";
        System.out.println(camelCase2Underscore(param));
    }//from   w ww.  j a va  2 s  .c om

    public static String camelCase2Underscore(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_"
                    + mc.group().toLowerCase());
            i++;
        }
        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }
}

Related Tutorials