Java String Camel Case camelCase(String text)

Here you can find the source of camelCase(String text)

Description

Converts the given String to camel case.

License

LGPL

Declaration


public static String camelCase(String text) 

Method Source Code

//package com.java2s;
// Metawidget (licensed under LGPL)

public class Main {
    /**//w w w .j av  a  2s .co m
     * Converts the given String to camel case.
     * <p>
     * The first letter is lowercased, as per Java convention.
     */

    public static String camelCase(String text) {

        return camelCase(text, ' ');
    }

    /**
     * Converts the given String to camel case.
     * <p>
     * The first letter is lowercased, as per Java convention.
     */

    public static String camelCase(String text, char separator) {

        StringBuilder builder = new StringBuilder(text.length());

        // Convert separators to camel case

        int firstCharacter = -1;
        boolean lastWasSeparator = false;
        char[] chars = text.toCharArray();

        for (int loop = 0, length = chars.length; loop < length; loop++) {

            char c = chars[loop];

            if (c == separator) {
                lastWasSeparator = true;
                continue;
            }

            if (!Character.isLetter(c) && !Character.isDigit(c)) {
                continue;
            }

            if (firstCharacter == -1) {
                // Do the first character below
                firstCharacter = loop;
                continue;
            }

            if (lastWasSeparator) {
                builder.append(Character.toUpperCase(c));
                lastWasSeparator = false;
                continue;
            }

            builder.append(c);
        }

        // Do the first character. Special support in case the first *two* characters are
        // capitalized

        // TODO: DOB should be dob?

        if (firstCharacter != -1) {
            int nextCharacter = firstCharacter + 1;
            if (chars.length > nextCharacter
                    && (Character.isLetter(chars[nextCharacter]) || Character.isDigit(chars[nextCharacter]))
                    && Character.isUpperCase(chars[nextCharacter])) {
                builder.insert(0, chars[firstCharacter]);
            } else {
                builder.insert(0, Character.toLowerCase(chars[firstCharacter]));
            }
        }

        return builder.toString();
    }
}

Related

  1. camelCase(String s)
  2. camelCase(String str)
  3. CamelCase(String str)
  4. camelCase(String string, boolean firstUpper)
  5. camelCase(String text)
  6. camelCase(String text)
  7. camelCase(String text)
  8. camelCased(String str)
  9. camelCasedWord(String s)