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*///accept a string, like aCamelString//return a list containing strings, in this case, [a, Camel, String]
SOURCE : NumberComplement.javaimport java.util.LinkedList;public class CamelCaseString { public static LinkedList splitCamelCaseString(String s) { char[] cArray = s.toCharArray(); LinkedList al = new LinkedList(); al.add(0); // get all upper case letter index positions for (int i = 1; i < cArray.length; i++) { char c = cArray[i]; // add more interested index beyond upper case letter if (c >= 65 && c <= 90) { al.add(i); } } LinkedList strl = new LinkedList(); // this handles the all lower letter case if (al.size() == 1) { strl.add(s); return strl; } int prev = 0; int curr = 0; int begin = 0; for (int k = 1; k < al.size(); k++) { curr = al.get(k); if (curr == s.length() - 1) { } if (curr == prev + 1 && curr != s.length() - 1) { prev = curr; } else if (curr == prev + 1 && curr == s.length() - 1) { strl.add(s.substring(begin, curr + 1)); } else { strl.add(s.substring(prev, curr)); prev = curr; begin = curr; if (k == al.size() - 1) { strl.add(s.substring(curr, s.length())); } } } return strl; } public static void main(String[] args) { String s = "SamSung CamelString , specialCase"; System.out.println(splitCamelCaseString(s)); }} OUTPUT[Sam, Sung , Camel, String , special, Case]

0 comments :
Post a Comment