Capitalize the First Letter of a String in Java – 在Java中对字符串的第一个字母进行大写

最后修改: 2022年 10月 20日

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

1. Overview

1.概述

The Java standard library has provided the String.toUpperCase() method, which allows us to convert all letters in a string to upper case.

Java标准库提供了String.toUpperCase()方法,它允许我们将一个字符串中的所有字母转换为大写。

In this tutorial, we’ll learn how to convert a given string’s first character only to upper case.

在本教程中,我们将学习如何将一个给定的字符串的第一个字符只转换为大写。

2. Introduction to the Problem

2.对问题的介绍

An example can explain this problem quickly. Let’s say we have an input string:

一个例子可以快速解释这个问题。比方说,我们有一个输入字符串。

String INPUT = "hi there, Nice to Meet You!";

Given this INPUT string, here’s our expected result:

鉴于这个INPUT字符串,这里是我们的预期结果。

String EXPECTED = "Hi there, Nice to Meet You!";

As we can see, we only want the first character, ‘h‘, to be changed into ‘H‘. However, the remaining characters shouldn’t be modified.

我们可以看到,我们只想让第一个字符,’h‘,变成’H‘。然而,其余的字符不应该被修改

Of course, if the input string is empty, the result should be an empty string too:

当然,如果输入的字符串是空的,结果也应该是一个空字符串。

String EMPTY_INPUT = "";
String EMPTY_EXPECTED = "";

In this tutorial, we’ll address several solutions to the problem. For simplicity, we’ll use unit test assertions to verify if our solution works as expected.

在本教程中,我们将讨论该问题的几种解决方案。为了简单起见,我们将使用单元测试断言来验证我们的解决方案是否按预期工作。

3. Using the substring() Method

3.使用substring()方法

The first idea to solve the problem is to split the input string into two substrings. For example, we can split the INPUT string to “h” and “i there, Nice ….“. In other words, the first substring contains only the first character, and the other substring holds the remaining characters of the strings.

解决问题的第一个想法是将输入字符串分成两个子字符串。例如,我们可以将INPUT字符串分割为”h“和”i there, Nice ….“。换句话说,第一个子串只包含第一个字符,而另一个子串则包含字符串的其余字符。

Then, we can just apply the toUpperCase() method on the first substring and concatenate the second substring to solve the problem.

然后,我们只需在第一个子串上应用toUpperCase()方法,并将第二个子串连接起来就可以解决问题

Java’s String class’s substring() method can help us to get the two substrings:

Java的String类的substring()方法可以帮助我们得到这两个子串。

  • INPUT.substring(0, 1) – substring 1 containing the first character
  • INPUT.substring(1) – substring 2 holding the rest of the characters

So next, let’s write a test to see if the solution works:

那么接下来,让我们写一个测试,看看这个解决方案是否有效。

String output = INPUT.substring(0, 1).toUpperCase() + INPUT.substring(1);
assertEquals(EXPECTED, output);

If we run the test, it passes. However, if our input is an empty string, this approach will raise IndexOutOfBoundsException. This is because the end-index (1) is greater than the empty string’s length (0) when we call INPUT.substring(1):

如果我们运行这个测试,它就会通过。然而,如果我们的输入是一个空字符串,这种方法将引发IndexOutOfBoundsException。这是因为当我们调用INPUT.substring(1)时,末端索引(1)大于空字符串的长度(0)。

assertThrows(IndexOutOfBoundsException.class, () -> EMPTY_INPUT.substring(1));

Further, we should note that if the input string is null, this approach will throw NullPointerException.

此外,我们应该注意,如果输入的字符串是null,这种方法将抛出NullPointerException

Therefore, before using the substring approach, we need to check and ensure the input string is not null or empty.

因此,在使用子串方法之前,我们需要检查并确保输入字符串不是null或空的

4. Using the Matcher.replaceAll() Method

4.使用Matcher.replaceAll()方法

Another idea to solve the problem is to use regex (“^.“) to match the first character and convert the matched group to upper case.

另一个解决问题的想法是使用regex(”^.“)来匹配第一个字符,并将匹配的组转换为大写。

It wasn’t an easy task before Java 9. This is because Matcher‘s replacement methods, such as replaceAll() and replaceFirst(), don’t support a Function object or a lambda expression replacer. However, this has changed in Java 9.

这在 Java 9 之前并不是一件容易的事情。这是因为 Matcher 的替换方法,例如 replaceAll()replaceFirst(), 不支持 Function 对象或 lambda expression replacer。然而,这在Java 9中有所改变。

Since Java 9, Matcher‘s replacement methods support a Function object as the replacer. That is to say, we can use a function to process the matched character sequence and fulfill the replacement. Of course, to solve our problem, we just need to call the toUpperCase() method on the matched character:

从Java 9开始,Matcher的替换方法支持使用Function对象作为替换者。也就是说,我们可以使用一个函数来处理匹配的字符序列并完成替换。当然,为了解决我们的问题,我们只需要对匹配的字符调用toUpperCase()方法。

String output = Pattern.compile("^.").matcher(INPUT).replaceFirst(m -> m.group().toUpperCase());
assertEquals(EXPECTED, output);

The test passes if we give it a run.

如果我们让它运行一下,测试就会通过。

If the regex matches nothing, the replacement won’t happen. Therefore, this solution works for empty input strings as well:

如果重词没有匹配任何东西,就不会发生替换。因此,这个解决方案对空输入字符串也适用

String emptyOutput = Pattern.compile("^.").matcher(EMPTY_INPUT).replaceFirst(m -> m.group().toUpperCase());
assertEquals(EMPTY_EXPECTED, emptyOutput);

It’s worth mentioning that if the input string is null, this solution will throw NullPointerException too. So, we still need to do a null check before we use it.

值得一提的是,如果输入的字符串是null,这个解决方案也会抛出NullPointerException。所以,我们在使用它之前仍然需要进行null检查。

5. Using StringUtils From Apache Commons Lang 3

5.使用StringUtils来自Apache Commons Lang 3

Apache Commons Lang3 is a popular library. It ships with a lot of handy utility classes and extends the functionality of the standard Java library.

Apache Commons Lang3是一个流行的库。它带有很多方便的实用类,并扩展了标准Java库的功能。

Its StringUtils class provides the capitalize() method, which solves our problem directly.

StringUtils类提供capitalize()方法,直接解决我们的问题。

To use the library, let’s first add the Maven dependency:

要使用该库,我们首先要添加Maven依赖性

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

Then, as usual, let’s create a test to see how it works:

然后,像往常一样,让我们创建一个测试,看看它是如何工作的。

String output = StringUtils.capitalize(INPUT);
assertEquals(EXPECTED, output);

The test passes if we execute it. As we can see, we simply call StringUtils.capitalize(INPUT). Then the library does the job for us.

如果我们执行它,测试就会通过。正如我们所看到的,我们简单地调用StringUtils.capitalize(INPUT)。然后库就为我们完成了工作。

It’s worth mentioning that the StringUtils.capitalize() method is null-safe and works for empty input strings as well:

值得一提的是,StringUtils.capitalize()方法是无效安全的,对空输入字符串也有效

String emptyOutput = StringUtils.capitalize(EMPTY_INPUT);
assertEquals(EMPTY_EXPECTED, emptyOutput);
String nullOutput = StringUtils.capitalize(null);
assertNull(nullOutput);

6. Conclusion

6.结语

In this article, we’ve learned how to convert the first character of a given string to upper case.

在这篇文章中,我们已经学会了如何将一个给定字符串的第一个字符转换为大写。

As always, the full code used in the article is available over on GitHub.

一如既往,文章中所使用的完整代码可在GitHub上获得