Java String Underscore toUnderscoreCase(final String s)

Here you can find the source of toUnderscoreCase(final String s)

Description

Converts an optionally camel-cased character sequence (e.g.

License

Apache License

Parameter

Parameter Description
s The text to convert.

Return

A underscore-cased version of the given text.

Declaration

public static String toUnderscoreCase(final String s) 

Method Source Code

//package com.java2s;
/*// w ww . ja  v  a2 s .c o m
 * Copyright 2012 Daniel Bechler
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Converts an optionally camel-cased character sequence (e.g. ThisIsSparta) into underscore-case (e.g.
     * this_is_sparta).
     *
     * @param s The text to convert.
     *
     * @return A underscore-cased version of the given text.
     */
    public static String toUnderscoreCase(final String s) {
        final char[] chars = s.toCharArray();
        final StringBuilder sb = new StringBuilder();
        char previousChar = 0;
        for (final char aChar : chars) {
            if (Character.isUpperCase(aChar)) {
                if (previousChar != 0) {
                    sb.append('_');
                }
                sb.append(Character.toLowerCase(aChar));
            } else {
                sb.append(aChar);
            }
            previousChar = aChar;
        }
        return sb.toString();
    }
}

Related

  1. toUnderscore(final String input, final boolean plural)
  2. toUnderscore(String s)
  3. toUnderscore(String text)
  4. toUnderscore(String v)
  5. toUnderscoreCase(String name)
  6. toUnderScoreCase(String s)
  7. toUnderScoreCase(String s)
  8. toUnderscored(String name)