Java method for spliting a camelcase string

This Java method accepts a camel case string, and returns a linked list of splitted strings. It has been designed to handle various kinds of different cases and fully tested and good to use.

Handling camel case in Java involves a lot of styles, this methods can handle the following cases:

  • Regular camel case names, e.g., “camelCaseName” -> [camel, Case, Name]
  • Single word class names, e.g., “Classname” -> [Classname]
  • All lower case names, e.g., “lower” -> [lower]
  • All upper case names, e.g., “UPPER” -> [UPPER]
  • speical cases, e.g., “speicalCASE” -> [speical, CASE]

If you want to handle numbers in camel case names, you can simple add number’s index in the following code below, which is very straightforward. (see comment in the code)

This method works for processing identifiers in my research, I hope it also works for you.

//accept a string, like aCamelString
//return a list containing strings, in this case, [a, Camel, String]
public static LinkedList<String> splitCamelCaseString(String s){
    LinkedList<String> result = new LinkedList<String>();	
    for (String w : s.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
    	result.add(w);
    }    
    return result;
}

The reason to use LinkedList is to keep the order of split strings according to its positions in original string.

2 thoughts on “Java method for spliting a camelcase string”

  1. First, what is the purpose of the following statement (line 34) in the above code? It looks unfinished. Doesn’t do anything, anyway:
    if(curr == s.length() – 1){

    }

    Second, your code above returns nothing for the word “JMSmith”.

    Third (and this a matter of interpretation and opinion), true CamelCase only capitalizes the first letter of an acronym, so that ParseHTML should really be ParseHtml. This means that the example word specialCASE should be returned as “(special, C, A, S, E)”

    Here is some code which I think is simpler (plus it returns a string, which for many applications might be more appropriate, and still preserves the order):

    public static String insertSpaceInMultiCaseStringAtCaps(String s) {
    char[] cArray = s.toCharArray();
    StringBuffer result = new StringBuffer();
    result = result.append(cArray[0]);
    // Start at 1 because even if it’s upper case, you don’t want to insert a blank

    // (and then trim when you return the result)
    for (int i = 1; i = 65 && c <= 90) {
    result.append(" "+c);
    } else result.append(c);
    }
    return result.toString();
    }

    The same functionality could probably be performed with replaceAll and a complex regular expression.

Leave a Comment