snakify string - Android java.lang

Android examples for java.lang:String Case

Description

snakify string

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static String snakify(String original) {
        if (original == null || original.length() == 0)
            return "";

        StringBuilder builder = new StringBuilder();
        Pattern p = Pattern.compile("[A-Z][a-z0-9]+");
        Matcher m = p.matcher(original);
        String word;/*  w  w  w.ja va  2  s . c o m*/
        while (m.find()) {
            word = m.group();
            builder.append(word.toLowerCase());
            if (!m.hitEnd()) {
                builder.append('_');
            }
        }
        if (builder.length() == 0) {
            return original.toLowerCase();
        }
        return builder.toString();
    }

}

Related Tutorials