转换格式全名模式字符串

时间:2017-12-28 04:07:16

标签: java string pattern-matching

我有一个String" adam levine"。如何将每个单词的第一个字母转换为大写,如#34; Adam Levine"?

String line = "adam levine";
line = line.substring(0, 1).toUpperCase() + line.substring(1);
System.out.println(line); // Adam levine

1 个答案:

答案 0 :(得分:3)

private static final Pattern bound = Pattern.compile("\\b(\\w)");

public static String titleize(final String input) {
    StringBuffer sb = new StringBuffer(input.length());
    Matcher mat = bound.matcher(input);
    while (mat.find()) {
        mat.appendReplacement(sb, mat.group().toUpperCase());
    }
    mat.appendTail(sb);
    return sb.toString();
}