Capitalize the First Letter of Each Word in a String – 将字符串中每个单词的第一个字母大写

最后修改: 2023年 10月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this short tutorial, we’ll shed light on how to capitalize the first character of each word of a particular string in Java.

在本简短教程中,我们将介绍如何在 Java 中将特定字符串中每个单词的第一个字符大写。

First, we’re going to explain how to do it using JDK built-in solutions. Then, we’ll demonstrate how to accomplish the same outcome using external libraries such as Apache Commons.

首先,我们将介绍如何使用 JDK 内置解决方案来实现这一目标。然后,我们将演示如何使用 Apache Commons 等外部库实现同样的结果。

2. Introduction to the Problem

2.问题介绍

The main objective here is to convert the first letter of each word in a given string to uppercase. For instance, let’s say we have an input string:

主要目的是将给定字符串中每个单词的第一个字母转换为大写字母。例如,假设我们有一个输入字符串:

String input = "Hi my name is azhrioun";

So, we expect to have an output where each word starts with an uppercase character:

因此,我们希望输出的结果是每个单词都以大写字母开头:

String output = "Hi My Name Is Azhrioun";

The basic idea to tackle the problem is splitting the input string into several words. Then, we can use different methods and classes to capitalize the first character of each returned word.

解决该问题的基本思路是将输入字符串分割成多个单词。然后,我们可以使用不同的方法和类来大写每个返回单词的第一个字符。

So, let’s take a close look at each approach.

那么,让我们仔细看看每一种方法。

3. Using Character#toUpperCase

3.使用 Character#toUpperCase 字符转大写</em

toUpperCase() provides the easiest way to achieve our goal. As the name indicates, this method converts a given character to uppercase.

toUpperCase()为实现我们的目标提供了最简单的方法。正如其名所示,该方法将给定字符转换为大写字母

So here, we’ll be using it to convert the first character of each word of our string:

在这里,我们将用它来转换字符串中每个单词的第一个字符:

static String usingCharacterToUpperCaseMethod(String input) {
    if (input == null || input.isEmpty()) {
        return null;
    }

    return Arrays.stream(input.split("\\s+"))
      .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
      .collect(Collectors.joining(" "));
}

As we can see, we started by checking if our string is null or empty to avoid potential NullPointerException. Then, we used the split() method to divide our input string into multiple words.

正如我们所看到的,我们首先检查字符串是否为 null 或空,以避免潜在的 NullPointerException. 然后,我们使用 split() 方法将输入字符串分成多个单词

Furthermore, we used charAt(0) to get the first character of each word. Then, we applied toUpperCase() to the returned character. Afterward, we concatenated the uppercase character with the rest of the word using the + operator and substring(1).

此外,我们使用 charAt(0) 获取每个单词的第一个字符。然后,我们对返回的字符应用 toUpperCase() 。然后,我们使用 + 操作符substring(1) 将大写字符与单词的其余部分连接起来。

Finally, we used Collectors#joining to join each capitalized word in a single string back again.

最后,我们使用Collectors#joining将单个字符串中的每个大写单词重新连接起来。

Now, let’s add a test case for our method:

现在,让我们为我们的方法添加一个测试用例:

@Test
void givenString_whenUsingCharacterToUpperCaseMethod_thenCapitalizeFirstCharacter() {
    String input = "hello baeldung visitors";

    assertEquals("Hello Baeldung Visitors", CapitalizeFirstCharacterEachWordUtils.usingCharacterToUpperCaseMethod(input));
}

4. Using String#toUpperCase

4.使用 String#toUpperCase

The String class provides its own version of the toUpperCase() method. So, let’s rewrite the previous example using String#toUpperCase:

String 类提供了自己版本的 toUpperCase() 方法。因此,让我们使用 String#toUpperCase 重写前面的示例:

static String usingStringToUpperCaseMethod(String input) {
    return Arrays.stream(input.split("\\s+"))
      .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
      .collect(Collectors.joining(" "));
}

As shown above, we used substring(0, 1) to extract the first character of each word as a String. Then, we called the toUpperCase() method to convert it to uppercase. Subsequently, we used the same mechanism as before to concatenate and join the returned words.

如上所示,我们使用 substring(0, 1)String 的形式提取每个单词的第一个字符。然后,我们调用 toUpperCase() 方法将其转换为大写。随后,我们使用与之前相同的机制来连接返回的单词。

Let’s write the test for this approach:

让我们为这种方法编写测试程序:

@Test
void givenString_whenUsingSubstringMethod_thenCapitalizeFirstCharacter() {
    String input = "Hi, my name is azhrioun";

    assertEquals("Hi, My Name Is Azhrioun", CapitalizeFirstCharacterEachWordUtils.usingStringToUpperCaseMethod(input));
}

Please bear in mind that, unlike String#toUpperCase, Character#toUpperCase is a static method. Another key difference is that String#toUpperCase produces a new String, whereas Character#toUpperCase returns a new char primitive.

请记住,与 String#toUpperCase 不同,Character#toUpperCase 是一个静态方法。另一个主要区别是,String#toUpperCase 产生一个新的 StringCharacter#toUpperCase 返回一个新的 char 基元。

5. Using StringUtils From Apache Commons Lang3

5.使用来自 Apache Commons Lang 的 StringUtils3

Alternatively, we can use the Apache Commons Lang3 library to address our central question. First, we need to add its dependency to our pom.xml:

或者,我们可以使用 Apache Commons Lang3 库来解决我们的核心问题。首先,我们需要将 其依赖关系添加到 pom.xml 中:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

This library provides the StringUtils class to manipulate and handle strings in a null-safe manner.

该库提供了 StringUtils 类,用于以空安全方式操作和处理字符串。

So, let’s see how we can use this utility class to capitalize each word of a specific string:

那么,让我们来看看如何使用这个实用工具类来大写特定字符串中的每个单词:

static String usingStringUtilsClass(String input) {
    return Arrays.stream(input.split("\\s+"))
      .map(StringUtils::capitalize)
      .collect(Collectors.joining(" "));
}

Here, we used the capitalize() method which, as the name implies, converts the first character to uppercase. The remaining characters of the given string are not changed.

在这里,我们使用了 capitalize() 方法,顾名思义,该方法将第一个字符转换为大写字母。给定字符串的其余字符不会改变

Lastly, let’s confirm our method using a new test case:

最后,让我们用一个新的测试用例来确认我们的方法:

@Test
void givenString_whenUsingStringUtilsClass_thenCapitalizeFirstCharacter() {
    String input = "life is short the world is wide";

    assertEquals("Life Is Short The World Is Wide", CapitalizeFirstCharacterEachWordUtils.usingStringUtilsClass(input));
}

6. Using WordUtils From Apache Commons Text

6.从 Apache Commons 文本中使用 WordUtils

Another solution would be using the Apache Commons Text library. Without further ado, let’s add its dependency to the pom.xml file:

另一种解决方案是使用 Apache Commons Text 库。话不多说,让我们将 其依赖关系添加到 pom.xml 文件中:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>

Typically, this library comes with a set of ready-to-use classes and methods for string operations. Among these classes, we find WordUtils.

通常情况下,该库带有一组可立即使用的类和方法,用于字符串操作。在这些类中,我们可以找到 WordUtils

The WordUtils#capitalizeFully method offers the most concise and straightforward way to tackle our problem. This method converts all the whitespace-separated words into capitalized words.

WordUtils#capitalizeFully方法为解决我们的问题提供了最简洁明了的方法。该方法将所有空白分隔的单词转换为大写单词

Please note that this method handles null input gracefully. So, we don’t need to check whether our input string is null or not.

请注意,此方法可以优雅地处理 null 输入。因此,我们无需检查输入字符串是否为 null

Now, let’s add another test case to make sure that everything works as expected:

现在,让我们再添加一个测试用例,以确保一切按预期运行:

@Test
void givenString_whenUsingWordUtilsClass_thenCapitalizeFirstCharacter() {
    String input = "smile sunshine is good for your teeth";

    assertEquals("Smile Sunshine Is Good For Your Teeth", WordUtils.capitalizeFully(input));
}

7. Conclusion

7.结论

In this short article, we explored different ways to capitalize the first letter of each word of a given string in Java.

在这篇短文中,我们探讨了在 Java 中将给定字符串中每个单词的首字母大写的不同方法。

First, we explained how to achieve this using the JDK. Then, we illustrated how to answer our central question using third-party libraries.

首先,我们解释了如何使用 JDK 来实现这一目标。然后,我们说明了如何使用第三方库来回答我们的核心问题。

As always, the code used in this article can be found over on GitHub.

与往常一样,本文中使用的代码可以在 GitHub 上找到