我想以编程方式根据字典(!)大写字符串中的单词。它应该与Java variable and method naming conventions中的CamelCase
类似。给定是一个全小写的字符串。找到最可能的Java约定套管。
我用现有的字典文件和一个用于检查给定String
是否是字典的一部分的类开始here
。困难在于找到正确或最有可能的substrings
。你会如何改善这个?
public String capitalizeWords(String text)
{
text = text.toLowerCase();
StringBuilder capitalizedWordBuilder = new StringBuilder();
int firstWordLength = text.length();
int beginIndex = 0;
while (true)
{
String subText = text.substring(beginIndex, firstWordLength);
if (contains(subText))
{
String word = capitalizeFirst(subText);
capitalizedWordBuilder.append(word);
beginIndex += word.length();
firstWordLength = text.length() + 1;
}
firstWordLength--;
if (beginIndex == firstWordLength && beginIndex == text.length())
{
String capitalized = capitalizedWordBuilder.toString();
return deCapitalizeFirst(capitalized);
}
}
}
private String capitalizeFirst(String text)
{
if (text.length() < 2)
{
return text;
}
return Character.toUpperCase(text.charAt(0)) + text.substring(1);
}
private String deCapitalizeFirst(String text)
{
if (text.length() < 2)
{
return text;
}
return Character.toLowerCase(text.charAt(0)) + text.substring(1);
}
示例运行:
javaisawesome - &gt; javaIsAwesome(好)
thisisastring - &gt; thisIsAstrIng( Bad )