Returns a lowercase string consisting of all initials of the words in the given String. - Java java.lang

Java examples for java.lang:String Case

Description

Returns a lowercase string consisting of all initials of the words in the given String.

Demo Code

/**// w  w w. j  a va  2s.c o m
 * Copyright (c) Red Hat, Inc., contributors and others 2013 - 2014. All rights reserved
 *
 * Licensed under the Eclipse Public License version 1.0, available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "java2s.com";
        System.out.println(getCamelCase(s));
    }

    /**
     * Returns a lowercase string consisting of all initials of the words in the
     * given String. Words are separated by whitespace and other special
     * characters, or by uppercase letters in a word like CamelCase.
     * 
     * @param s
     *            the string
     * @return a lowercase string containing the first character of every wordin
     *         the given string.
     */
    public static String getCamelCase(String s) {
        StringBuffer result = new StringBuffer();
        if (s.length() > 0) {
            int index = 0;
            while (index != -1) {
                result.append(s.charAt(index));
                index = getNextCamelIndex(s, index + 1);
            }
        }
        return result.toString().toLowerCase();
    }

    /**
     * Returns the next index to be used for camel case matching.
     * 
     * @param s the string
     * @param index the index
     * @return the next index, or -1 if not found
     */
    public static int getNextCamelIndex(String s, int index) {
        char c;
        while (index < s.length()
                && !(isSeparatorForCamelCase(c = s.charAt(index)))
                && Character.isLowerCase(c)) {
            index++;
        }
        while (index < s.length()
                && isSeparatorForCamelCase(c = s.charAt(index))) {
            index++;
        }
        if (index >= s.length()) {
            index = -1;
        }
        return index;
    }

    /**
     * Returns true if the given character is to be considered a separator
     * for camel case matching purposes.
     * 
     * @param c the character
     * @return true if the character is a separator
     */
    public static boolean isSeparatorForCamelCase(char c) {
        return !Character.isLetterOrDigit(c);
    }
}

Related Tutorials