如何将字符串中每个单词的首字母转换为大写?

95

我有一个字符串:"hello good old world",我想将每个单词的第一个字母改为大写,而不是使用 .toUpperCase() 将整个字符串转换为大写。是否存在一个现成的 Java 工具可以完成这个任务?

16个回答

128

可以看一下 ACL 的 WordUtils

WordUtils.capitalize("your string") == "Your String"

@kd 我试过了http://www.google.at/search?q=java+word+uppercase,无论如何还是谢谢。 - Chris
1
WordUtils.capitalize("your string") 将会是 "Your String"。 - Raymond Chenon
WordUtils已被弃用。 - MiladiuM
1
@MiladiuM 只是因为它已经移动到另一个库:commons-text - Christopher Schultz

70

以下是代码

    String source = "hello good old world";
    StringBuffer res = new StringBuffer();

    String[] strArr = source.split(" ");
    for (String str : strArr) {
        char[] stringArray = str.trim().toCharArray();
        stringArray[0] = Character.toUpperCase(stringArray[0]);
        str = new String(stringArray);

        res.append(str).append(" ");
    }

    System.out.print("Result: " + res.toString().trim());

1
你没有理解问题,你只是将第一个单词的第一个字母大写了。字符串中有几个单词,你必须将每个单词的第一个字母大写。 - Chris
4
+1 我喜欢这个,它很简单。但是需要将其放在一个循环中,以满足问题的需求。 - GingerHead
这可以稍微改进一下。长度已知,因此您可以预先分配StringBuilder的长度。既然您将调用StringBuilder.append,则不必在每次循环迭代中创建新的char[]String:只需附加大写字母,然后使用String.charAtString.substring添加单词的其余部分。最后,您可能应该允许传入一个Locale,以便使用区域设置敏感的String.toUpperCase(Locale) - Christopher Schultz

53
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);

45

我不知道是否有一个函数可以完成此任务,但如果没有现成的函数,这段代码可以实现:

String s = "here are a bunch of words";

final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
  if(i>0) result.append(" ");      
  result.append(Character.toUpperCase(words[i].charAt(0)))
        .append(words[i].substring(1));

}

1
不错,但是words[i].substring(1)对于像“a”这样的单字母词无法正常工作。需要先检查长度。 - Reactgular

19
import org.apache.commons.lang.WordUtils;

public class CapitalizeFirstLetterInString {
    public static void main(String[] args) {
        // only the first letter of each word is capitalized.
        String wordStr = WordUtils.capitalize("this is first WORD capital test.");
        //Capitalize method capitalizes only first character of a String
        System.out.println("wordStr= " + wordStr);

        wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
        // This method capitalizes first character of a String and make rest of the characters lowercase
        System.out.println("wordStr = " + wordStr );
    }
}

输出:

这是第一个单词大写测试。

这是第一个单词大写测试。


// 一行代码转换 String sss = "Salem this is me"; String str= sss.replaceFirst(String.valueOf(sss.charAt(0)),String.valueOf((char)(sss.charAt(0)-32))); // 将字符串首字母大写 System.out.println(str); - Ben Rhouma Zied

13

这里是一个非常简单、紧凑的解决方案。 str 包含你想要大写的变量。

StringBuilder b = new StringBuilder(str);
int i = 0;
do {
  b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
  i =  b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());

System.out.println(b.toString());

最好使用StringBuilder,因为String是不可变的,对于每个单词生成新的字符串效率低下。


在for循环内部使用一个变量,我是否也需要使用StringBuffer呢?即使每次循环迭代时变量值都会改变??哦天啊。@binkdm - gumuruh

11

尝试比将字符串拆分为多个字符串更加节省内存,并使用Darshana Sri Lanka所示的策略。此外,该方法处理单词之间的所有空白字符,而不仅仅是“ ”字符。

public static String UppercaseFirstLetters(String str) 
{
    boolean prevWasWhiteSp = true;
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (Character.isLetter(chars[i])) {
            if (prevWasWhiteSp) {
                chars[i] = Character.toUpperCase(chars[i]);    
            }
            prevWasWhiteSp = false;
        } else {
            prevWasWhiteSp = Character.isWhitespace(chars[i]);
        }
    }
    return new String(chars);
}

还要注意,在EditText视图中,您可以指定android:inputType="textCapWords",这将自动大写每个单词的第一个字母。这样可以避免调用此方法。 - user877139
这对我来说非常完美。感谢您的解决方案。我想现在我们都知道EditText可以将单词大写,但我需要一个输入不是进入EditText的解决方案。 - Daniel Ochoa
使用android:inputType="textCapWords" 只更改键盘的初始大写状态,如果用户按返回键,仍然可以输入小写字母,因此,如果需要强制使用首字母大写,则需要进行提交前处理。 - ZacWolf

7
    String s = "java is an object oriented programming language.";      
    final StringBuilder result = new StringBuilder(s.length());    
    String words[] = s.split("\\ "); // space found then split it  
    for (int i = 0; i < words.length; i++) 
         {
    if (i > 0){
    result.append(" ");
    }   
    result.append(Character.toUpperCase(words[i].charAt(0))).append(
                words[i].substring(1));   
    }  
    System.out.println(result);  

输出: Java是一种面向对象的编程语言。


4

此外,您可以查看StringUtils库。它有很多很酷的东西。


你理解了这个问题吗?你检查了被接受的答案吗?你在发布前验证了链接吗?你检查了主题的日期吗? - BalusC
1
+1 对于 StringUtils,但请更新您的链接 :) - icl7126

3

在阅读几篇以上的答案后,我的代码如下。

/**
 * Returns the given underscored_word_group as a Human Readable Word Group.
 * (Underscores are replaced by spaces and capitalized following words.)
 * 
 * @param pWord
 *            String to be made more readable
 * @return Human-readable string
 */
public static String humanize2(String pWord)
{
    StringBuilder sb = new StringBuilder();
    String[] words = pWord.replaceAll("_", " ").split("\\s");
    for (int i = 0; i < words.length; i++)
    {
        if (i > 0)
            sb.append(" ");
        if (words[i].length() > 0)
        {
            sb.append(Character.toUpperCase(words[i].charAt(0)));
            if (words[i].length() > 1)
            {
                sb.append(words[i].substring(1));
            }
        }
    }
    return sb.toString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接