Last active
August 29, 2015 14:15
-
-
Save glapworth/73582950904693c1d11d to your computer and use it in GitHub Desktop.
TitleCase in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String TITLE_CASE(String fullname) { | |
String[] word_splitters = {" ", "-", "o^[']", "l^[']", "d^[']", "St^[.]", "Mc","O'", "L^[']", "D^[']", "mc"}; | |
String[] lowercase_exceptions = {"the", "van", "den", "von", "und", "der", "de", "da", "of", "and", "l'", "d'"}; | |
String[] uppercase_exceptions = {"II","III", "IV", "VI", "VII", "VIII", "IX"}; | |
ArrayList<String> new_words = new ArrayList<String>(); | |
fullname = fullname.toLowerCase(); | |
for (String delimiter : word_splitters) { | |
String[] split_words = fullname.split(delimiter); | |
new_words.clear(); | |
for (String word : split_words) { | |
if (in_array(word.toUpperCase(), uppercase_exceptions)) { | |
word = word.toUpperCase(); | |
} else { | |
if (!in_array(word, lowercase_exceptions)) { | |
if(word.length() > 0) { | |
word = word.substring(0, 1).toUpperCase() + word.substring(1); | |
} | |
} | |
} | |
new_words.add(word); | |
} | |
if (in_array(delimiter, lowercase_exceptions)) { | |
delimiter = delimiter.toLowerCase(); | |
} | |
String[] stringArray = new_words.toArray(new String[new_words.size()]); | |
fullname = implode(stringArray,delimiter); | |
} | |
return fullname; | |
} | |
public static boolean in_array(String inputString, String[] items) { | |
for(int i =0; i < items.length; i++) { | |
if(inputString.equals(items[i])) { | |
return true; | |
} | |
} | |
return false; | |
} | |
public static String implode(String[] inputArray, String glueString) { | |
String output = ""; | |
if (inputArray.length > 0) { | |
StringBuilder sb = new StringBuilder(); | |
sb.append(inputArray[0]); | |
for (int i=1; i<inputArray.length; i++) { | |
sb.append(glueString); | |
sb.append(inputArray[i]); | |
} | |
output = sb.toString(); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment