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.
<pre><code> String foo = "bar"; </code></pre>
-
Lian
-
Tihamer