Java String Underscore underscored(String string)

Here you can find the source of underscored(String string)

Description

Convert from CamelCase to underscored: MyModel -> my_model.

License

Open Source License

Parameter

Parameter Description
string a parameter

Declaration

public static String underscored(String string) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Oobium, Inc./* w  w w .  j a  v a2 s.c  o  m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Jeremy Dowdall <jeremy@oobium.com> - initial API and implementation
 ******************************************************************************/

public class Main {
    /**
     * Convert from CamelCase to underscored: MyModel -> my_model.
     * null values are returned as a String -> "null".
     * All returned characters are lower case.
     * @param string
     * @return
     */
    public static String underscored(String string) {
        return separated(string, '_');
    }

    public static String separated(String string, char separator) {
        if (string == null || string.length() == 0) {
            return "null";
        }

        String s = string.trim().replaceAll("[\\s]+", Character.toString(separator));
        StringBuilder sb = new StringBuilder();
        char[] ca = s.toCharArray();
        for (int i = 0; i < ca.length; i++) {
            if (Character.isUpperCase(ca[i])) {
                if (i != 0 && Character.isLetterOrDigit(ca[i - 1])) {
                    if (Character.isUpperCase(ca[i - 1])) {
                        if (i < ca.length - 1 && Character.isLetter(ca[i + 1])
                                && !Character.isUpperCase(ca[i + 1])) {
                            sb.append(separator);
                        }
                    } else {
                        sb.append(separator);
                    }
                }
                sb.append(Character.toLowerCase(ca[i]));
            } else {
                sb.append(ca[i]);
            }
        }
        return sb.toString();
    }
}

Related

  1. underscoreAllWhitespace(String str)
  2. underscoreAndLowercase(String s)
  3. underScoreBreakToCaseBreak (final String s)
  4. underscoreCase(String s)
  5. underScoreCase2CamelCase(String str)
  6. underscoredToCamel(String string)
  7. underscoreName(String camelCaseName)
  8. underscoreName(String name)
  9. underscoreSpaces(String input)