首先,请不要将其标记为重复。
我有一个非常具体的问题。 我必须把每个单词的第一个字母大写。问题是,当一个单词开始时我无法找到。
例如,我给了String:
0nd0-cathay bank (federal saving)
输出应如下:
0Nd0-Cathay Bank (Federal Saving).
目前,我有以下标题案例方法:
public static String toTitleCase(String str)
{
if (str == null)
return "";
boolean space = true;
StringBuilder builder = new StringBuilder(str);
final int len = builder.length();
for (int i=0; i < len; ++i)
{
char c = builder.charAt(i);
if (space)
{
if (!Character.isWhitespace(c))
{
// Convert to title case and switch out of whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
space = false;
}
}
else if (Character.isWhitespace(c))
{
space = true;
}
else
{
builder.setCharAt(i, Character.toLowerCase(c));
}
}
return builder.toString();
}
谢谢大家。
答案 0 :(得分:1)
您可以使用以下解决方案与正则表达式(虽然不是最漂亮)。
String input = "0nd0-cathay bank (federal saving)";
// case-sensitive Pattern:
// | group 1: first letter
// | | group 2: any other character if applicable
// | | | word boundary
Pattern p = Pattern.compile("([a-z])(.*?)\\b");
// Pattern for all capital letters
// Pattern p = Pattern.compile("([A-Z])(.*?)\\b");
// initializing StringBuffer for appending
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(input);
// iterating over matches
while (m.find()) {
// appending replacement:
// | 1st letter capitalized
// | | concatenated with...
// | | | any other character
// | | | within word boundaries
m.appendReplacement(sb, m.group(1).toUpperCase().concat(m.group(2)));
// Replacement for all capital letters
// m.appendReplacement(sb, m.group(1).concat(m.group(2).toLowerCase()));
}
// appending tail if any
m.appendTail(sb);
System.out.println(sb.toString());
<强>输出强>
0Nd0-Cathay Bank (Federal Saving)
备注强>
0nd0
变为0Nd0
。\\b
前加上一个单词边界(Pattern
)。答案 1 :(得分:1)
这可能对您有用:
public static void main(String[] args) {
String s = "0nd0-cathay bank (federal saving)";
Pattern p = Pattern.compile("(?<![a-z])([a-z])"); // negative look-behind. check if your char is not preceeded by another char.
Matcher m = p.matcher(s);
while (m.find()) {
char val = m.group(1).toUpperCase().charAt(0);
s = s.replaceFirst(m.group(1), String.valueOf(val));
}
System.out.println(s);
}
O / P:
0Nd0-Cathay Bank (Federal Saving)