在java中的String中的每个单词中首字母大写(但忽略特定单词)

时间:2014-02-23 11:01:25

标签: java string

任何人都可以告诉我为什么下面的代码打印1高街而不是1高街?:

    String propertyPageTitle = "1-the-high-street";
    propertyPageTitle = propertyPageTitle.replace("-", " ");
    WordUtils.capitalizeFully(propertyPageTitle);
    System.out.println(propertyPageTitle);

编辑以显示解决方案:

    String propertyPageTitle = "1-the-high-street";
    propertyPageTitle = propertyPageTitle.replace("-", " ");
    propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);
    System.out.println(propertyPageTitle);

假设我想忽略单词'和',如果它出现(我正在读取.csv的值)而不是改为标题?怎么会这样呢?

4 个答案:

答案 0 :(得分:1)

WordUtils.capitalizeFully不会更改原始字符串,而是返回大写字符串。

propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);

答案 1 :(得分:1)

这是因为capitalizeFully(String)的{​​{1}}会返回一个具有预期答案的WordUtils。所以试试:

String

然后它会起作用。

答案 2 :(得分:0)

String firstStr = "i am fine";
String capitalizedStr = WordUtils.capitalizeFully(firstStr);
System.out.println(capitalizedStr);

应该返回以获取方法的输出。它对Java String

中的所有方法都很常见

答案 3 :(得分:0)

    String toBeCapped = "1 the high street and 2 low street";

    String[] tokens = toBeCapped.split("\\s");
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < tokens.length; i++) {
        if (!tokens[i].equalsIgnoreCase("and")) {
            char capLetter = Character.toUpperCase(tokens[i].charAt(0));
            builder.append(" ");
            builder.append(capLetter);
            builder.append(tokens[i].substring(1, tokens[i].length()));
        } else {
            builder.append(" and");
        }
    }
    toBeCapped = builder.toString().trim();
    System.out.println(toBeCapped);

输出:

1 The High Street and 2 Low Street