Returns the first word for the given long Name. - Java java.lang

Java examples for java.lang:char

Description

Returns the first word for the given long Name.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {


    /**//from   w  w w .j a va  2  s.c  o m
     * Returns the first word for the given longName.
     * For example if longName will be "StriBC", it will return "Stri". In general
     * it means it always return a substring from the beginning to the second upper
     * case character (which is 'B' in this case).
     *
     * @param longName whole type name
     * @return first camel case word as described above
     */
    public static String getCamelCaseFirstWord(String longName) {
        List<String> splittedPrefix = splitByUpperCases(longName);
        if (splittedPrefix.isEmpty()) {
            return "";
        } else {
            return splittedPrefix.get(0);
        }
    }

    /**
     * For the given prefix returns list of subPrefixes where each of them starts
     * with an uppercases letter. For example:
     *
     * If parameter will be "StrBui", this method will return list containing two Strings ("Str" and "Bui")
     * If parameter will be "NGC", this method will return three Strings ("N", "G", "C")
     *
     * @param prefix which we want to split
     * @return list of splitted prefixes
     */
    private static List<String> splitByUpperCases(String prefix) {
        List<String> splitedPrefixes = new ArrayList<String>();
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < prefix.length(); i++) {
            char actualChar = prefix.charAt(i);
            if (Character.isUpperCase(actualChar)) {

                // We found an upper case letter - save current context if it's
                // not empty, clear builder cache and continue with iteration

                if (builder.length() != 0) {
                    splitedPrefixes.add(builder.toString());
                }

                builder.delete(0, builder.length());
            }
            builder.append(actualChar);
        }
        splitedPrefixes.add(builder.toString()); // Save the last 'word'

        return splitedPrefixes;
    }
}

Related Tutorials