我的例程的一个主要限制是,它假设“ title case”是为所有语言环境统一定义的,并且由我使用过的相同的 case 约定表示,因此在这方面它没有 dfa 的代码有用。
public static String toDisplayCase(String s) {
final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized
StringBuilder sb = new StringBuilder();
boolean capNext = true;
for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}
public static String toTitleCase(String input) {
input = input.toLowerCase();
char c = input.charAt(0);
String s = new String("" + c);
String f = s.toUpperCase();
return f + input.substring(1);
}
public final class TitleCase {
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toLowerCase().toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
}
我最近也遇到了这个问题,不幸的是,很多名字都是从 Mc 和 Mac 开始的,我最终使用了一个 Scottb 的代码版本,我修改了它来处理这些前缀,所以它就在这里,以防有人想要使用它。
仍然有边缘情况下,这是错过了,但最坏的事情可能发生的是,一个字母将是小写时,它应该大写。
/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* Andrew MacNamara if processed as 2 strings.
* @param name
* @return correctly formatted name
*/
public static String getNameTitleCase (String name) {
final String ACTIONABLE_DELIMITERS = " '-/";
StringBuilder sb = new StringBuilder();
if (name !=null && !name.isEmpty()){
boolean capitaliseNext = true;
for (char c : name.toCharArray()) {
c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
sb.append(c);
capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
}
name = sb.toString();
if (name.startsWith("Mc") && name.length() > 2 ) {
char c = name.charAt(2);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,2));
sb.append (name.substring(2,3).toUpperCase());
sb.append (name.substring(3));
name=sb.toString();
}
} else if (name.startsWith("Mac") && name.length() > 3) {
char c = name.charAt(3);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,3));
sb.append (name.substring(3,4).toUpperCase());
sb.append (name.substring(4));
name=sb.toString();
}
}
}
return name;
}
/**
* Convert a string to title case in java (with tests).
*
* @author Sudipto Chandra
*/
public abstract class TitleCase {
/**
* Returns the character type. <br>
* <br>
* Digit = 2 <br>
* Lower case alphabet = 0 <br>
* Uppercase case alphabet = 1 <br>
* All else = -1.
*
* @param ch
* @return
*/
private static int getCharType(char ch) {
if (Character.isLowerCase(ch)) {
return 0;
} else if (Character.isUpperCase(ch)) {
return 1;
} else if (Character.isDigit(ch)) {
return 2;
}
return -1;
}
/**
* Converts any given string in camel or snake case to title case.
* <br>
* It uses the method getCharType and ignore any character that falls in
* negative character type category. It separates two alphabets of not-equal
* cases with a space. It accepts numbers and append it to the currently
* running group, and puts a space at the end.
* <br>
* If the result is empty after the operations, original string is returned.
*
* @param text the text to be converted.
* @return a title cased string
*/
public static String titleCase(String text) {
if (text == null || text.length() == 0) {
return text;
}
char[] str = text.toCharArray();
StringBuilder sb = new StringBuilder();
boolean capRepeated = false;
for (int i = 0, prev = -1, next; i < str.length; ++i, prev = next) {
next = getCharType(str[i]);
// trace consecutive capital cases
if (prev == 1 && next == 1) {
capRepeated = true;
} else if (next != 0) {
capRepeated = false;
}
// next is ignorable
if (next == -1) {
// System.out.printf("case 0, %d %d %s\n", prev, next, sb.toString());
continue; // does not append anything
}
// prev and next are of same type
if (prev == next) {
sb.append(str[i]);
// System.out.printf("case 1, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is not an alphabet
if (next == 2) {
sb.append(str[i]);
// System.out.printf("case 2, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is an alphabet, prev was not +
// next is uppercase and prev was lowercase
if (prev == -1 || prev == 2 || prev == 0) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(Character.toUpperCase(str[i]));
// System.out.printf("case 3, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is lowercase and prev was uppercase
if (prev == 1) {
if (capRepeated) {
sb.insert(sb.length() - 1, ' ');
capRepeated = false;
}
sb.append(str[i]);
// System.out.printf("case 4, %d %d %s\n", prev, next, sb.toString());
}
}
String output = sb.toString().trim();
output = (output.length() == 0) ? text : output;
//return output;
// Capitalize all words (Optional)
String[] result = output.split(" ");
for (int i = 0; i < result.length; ++i) {
result[i] = result[i].charAt(0) + result[i].substring(1).toLowerCase();
}
output = String.join(" ", result);
return output;
}
/**
* Test method for the titleCase() function.
*/
public static void testTitleCase() {
System.out.println("--------------- Title Case Tests --------------------");
String[][] samples = {
{null, null},
{"", ""},
{"a", "A"},
{"aa", "Aa"},
{"aaa", "Aaa"},
{"aC", "A C"},
{"AC", "Ac"},
{"aCa", "A Ca"},
{"ACa", "A Ca"},
{"aCamel", "A Camel"},
{"anCamel", "An Camel"},
{"CamelCase", "Camel Case"},
{"camelCase", "Camel Case"},
{"snake_case", "Snake Case"},
{"toCamelCaseString", "To Camel Case String"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"ABDTest", "Abd Test"},
{"title123Case", "Title123 Case"},
{"expect11", "Expect11"},
{"all0verMe3", "All0 Ver Me3"},
{"___", "___"},
{"__a__", "A"},
{"_A_b_c____aa", "A B C Aa"},
{"_get$It132done", "Get It132 Done"},
{"_122_", "122"},
{"_no112", "No112"},
{"Case-13title", "Case13 Title"},
{"-no-allow-", "No Allow"},
{"_paren-_-allow--not!", "Paren Allow Not"},
{"Other.Allow.--False?", "Other Allow False"},
{"$39$ldl%LK3$lk_389$klnsl-32489 3 42034 ", "39 Ldl Lk3 Lk389 Klnsl32489342034"},
{"tHis will BE MY EXAMple", "T His Will Be My Exa Mple"},
{"stripEvery.damn-paren- -_now", "Strip Every Damn Paren Now"},
{"getMe", "Get Me"},
{"whatSthePoint", "What Sthe Point"},
{"n0pe_aLoud", "N0 Pe A Loud"},
{"canHave SpacesThere", "Can Have Spaces There"},
{" why_underScore exists ", "Why Under Score Exists"},
{"small-to-be-seen", "Small To Be Seen"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"last one onTheList", "Last One On The List"}
};
int pass = 0;
for (String[] inp : samples) {
String out = titleCase(inp[0]);
//String out = WordUtils.capitalizeFully(inp[0]);
System.out.printf("TEST '%s'\nWANTS '%s'\nFOUND '%s'\n", inp[0], inp[1], out);
boolean passed = (out == null ? inp[1] == null : out.equals(inp[1]));
pass += passed ? 1 : 0;
System.out.println(passed ? "-- PASS --" : "!! FAIL !!");
System.out.println();
}
System.out.printf("\n%d Passed, %d Failed.\n", pass, samples.length - pass);
}
public static void main(String[] args) {
// run tests
testTitleCase();
}
}
以下是一些投入:
aCamel
TitleCase
snake_case
fromCamelCASEString
ABCTest
expect11
_paren-_-allow--not!
why_underScore exists
last one onTheList
我的成果是:
A Camel
Title Case
Snake Case
From Camel Case String
Abc Test
Expect11
Paren Allow Not
Why Under Score Exists
Last One On The List