converts string to ruby case, using the specified string delimiter - Java java.lang

Java examples for java.lang:String Case

Description

converts string to ruby case, using the specified string delimiter

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String value = "java2s.com";
        String delim = "java2s.com";
        System.out.println(snakeCase(value, delim));
    }//  w ww .java2 s.  c  o m

    /**
     * converts string to ruby case, using the specified string delimiter
     */
    public static String snakeCase(final String value, final String delim) {
        // check for null
        if (value == null || value.isEmpty()) {
            return "";
        }

        final StringBuilder result = new StringBuilder(value.length());
        final String[] parts = value.split(delim);
        if (parts != null && parts.length > 0) {
            boolean bMustUnderscore = false;
            for (final String part : parts) {
                if (part.length() > 1) {
                    if (bMustUnderscore) {
                        result.append("_");
                    }
                    result.append(part.toLowerCase());
                    bMustUnderscore = true;
                } else {
                    result.append(part);
                }
            }
        }

        return result.toString();
    }
}

Related Tutorials