【问题标题】:Changing first letter in a String to upper case in Java/Android [duplicate]在Java / Android中将字符串中的第一个字母更改为大写[重复]
【发布时间】:2019-06-02 14:19:13
【问题描述】:

我意识到 GoogleMaps 中的 AdminArea 名称是小写的(至少在波兰是这样),我决定在我的新(非常简单的)应用程序中以大写字母开头会更好看。 这段代码有意义吗?它对我有用,但我不确定这是否是最好的方法:

String firstLetter = listAddresses.get(0).getAdminArea().toUpperCase().charAt(0)+"";
String otherLetters = listAddresses.get(0).getAdminArea().substring(1);
String adminArea = firstLetter+otherLetters;

【问题讨论】:

  • 欢迎来到 Stack Overflow。我建议您访问我们的姊妹网站Code Review 以获取有关工作代码的反馈。请务必阅读他们的文档并遵循他们发布问题的指南。

标签: java android string uppercase


【解决方案1】:

考虑:org.apache.commons.lang3.StringUtils.capitalize:

public static String capitalize(final String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return str;
    }

    final char firstChar = str.charAt(0);
    final char newChar = Character.toTitleCase(firstChar);
    if (firstChar == newChar) {
        // already capitalized
        return str;
    }

    char[] newChars = new char[strLen];
    newChars[0] = newChar;
    str.getChars(1,strLen, newChars, 1);
    return String.valueOf(newChars);
}

【讨论】:

  • 这是来自 apache 库的实现吗?
  • @Code-Apprentice 是
猜你喜欢
  • 2023-03-09
  • 2013-02-21
  • 2011-03-07
  • 1970-01-01
  • 2017-03-20
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
相关资源
最近更新 更多