Count Spaces in a Java String – 计算一个Java字符串中的空格

最后修改: 2021年 9月 21日

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

1. Overview

1.概述

When we work with Java strings, sometimes we would like to count how many spaces are in a string.

当我们在处理Java字符串时,有时我们想计算一个字符串中有多少个空格。

There are various ways to get the result. In this quick tutorial, we’ll see how to get it done through examples.

有各种方法可以得到这个结果。在这个快速教程中,我们将通过实例来了解如何得到它。

2. The Example Input String

2.输入字符串的例子

First of all, let’s prepare an input string as the example:

首先,让我们准备一个输入字符串作为例子。

String INPUT_STRING = "  This string has nine spaces and a Tab:'	'";

The string above contains nine spaces and a tab character wrapped by single quotes. Our goal is to count space characters only in the given input string.

上面的字符串包含九个空格和一个由单引号包裹的Tab字符。我们的目标是只计算给定输入字符串中的空格字符

Therefore, our expected result is:

因此,我们的预期结果是。

int EXPECTED_COUNT = 9;

Next, let’s explore various solutions to get the right result.

接下来,让我们探讨各种解决方案,以获得正确的结果。

We’ll first solve the problem using the Java standard library, then we’ll solve it using some popular external libraries.

我们首先用Java标准库来解决这个问题,然后用一些流行的外部库来解决这个问题。

Finally, in this tutorial, we’ll address all solutions in unit test methods.

最后,在本教程中,我们将解决单元测试方法中的所有解决方案。

3. Using Java Standard Library

3.使用Java标准库

3.1. The Classic Solution: Looping and Counting

3.1.经典的解决方案 循环和计数

This is probably the most straightforward idea to solve the problem.

这可能是解决这个问题的最直接的想法。

We go through all the characters in the input string. Also, we maintain a counter variable and increment the counter once we see a space character.

我们遍历输入字符串中的所有字符。同时,我们维护一个计数器变量,一旦看到一个空格字符,就增加该计数器。

Finally, we’ll get the count of the spaces in the string:

最后,我们将得到字符串中空格的数量。

@Test
void givenString_whenCountSpaceByLooping_thenReturnsExpectedCount() {
    int spaceCount = 0;
    for (char c : INPUT_STRING.toCharArray()) {
        if (c == ' ') {
            spaceCount++;
        }
    }
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

3.2. Using Java 8’s Stream API

3.2.使用Java 8的流API

Stream API has been around since Java 8.

Stream API从Java 8开始就已经存在了。

Additionally, since Java 9, a new chars() method has been added to the String class to convert the char values from the String into an IntStream instance.

此外,自Java 9以来,一个新的chars()方法已被添加到String类中,用于将String中的char值转换为IntStream实例

If we’re working with Java 9 or later, we can combine the two features to solve the problem in a one-liner:

如果我们使用的是Java 9或更高版本,我们可以把这两个功能结合起来,用一句话解决这个问题。

@Test
void givenString_whenCountSpaceByJava8StreamFilter_thenReturnsExpectedCount() {
    long spaceCount = INPUT_STRING.chars().filter(c -> c == (int) ' ').count();
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

3.3. Using Regex’s Matcher.find() Method

3.3.使用Regex的Matcher.find()方法

So far, we’ve seen solutions that count by searching the space characters in the given string. We’ve used character == ‘ ‘ to check if a character is a space character.

到目前为止,我们已经看到了通过搜索给定字符串中的空格字符来计算的解决方案。我们已经使用character == ‘ ‘ 来检查一个字符是否是空格字符。

Regular Expression (Regex) is another powerful weapon to search strings, and Java has good support for Regex.

规则表达式(Regex)是搜索字符串的另一个有力武器,而Java对Regex有很好的支持。

Therefore, we can define a single space as a pattern and use the Matcher.find() method to check if the pattern is found in the input string.

因此,我们可以定义一个空格作为模式,并使用Matcher.find()方法来检查是否在输入字符串中找到该模式。

Also, to get the count of spaces, we increment a counter every time the pattern is found:

另外,为了得到空格的数量,我们在每次发现图案时都会递增一个计数器。

@Test
void givenString_whenCountSpaceByRegexMatcher_thenReturnsExpectedCount() {
    Pattern pattern = Pattern.compile(" ");
    Matcher matcher = pattern.matcher(INPUT_STRING);
    int spaceCount = 0;
    while (matcher.find()) {
        spaceCount++;
    }
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

3.4. Using the String.replaceAll() Method

3.4.使用String.replaceAll()方法

Using the Matcher.find() method to search and find spaces is pretty straightforward. However, since we’re talking about Regex, there can be other quick ways to count spaces.

使用Matcher.find()方法来搜索和查找空格是非常简单的。然而,由于我们谈论的是Regex,可以有其他快速方法来计算空格。

We know that we can do “search and replace” using the String.replaceAll() method.

我们知道,我们可以使用String.replaceAll()方法进行 “搜索和替换”。

Therefore, if we replace all non-space characters in the input string with an empty string, all spaces from the input will be the result.

因此,如果我们用一个空字符串替换输入字符串中的所有非空格字符,那么输入的所有空格都将成为结果

So, if we want to get the count, the length of the resulting string will be the answer. Next, let’s give this idea a try:

因此,如果我们想得到计数,所得字符串的长度将是答案。接下来,让我们试一试这个想法。

@Test
void givenString_whenCountSpaceByReplaceAll_thenReturnsExpectedCount() {
    int spaceCount = INPUT_STRING.replaceAll("[^ ]", "").length();
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

As the code above shows, we have just one line to get the count.

如上面的代码所示,我们只有一行来获得计数。

It’s worthwhile to mention that, in the String.replaceAll() call, we’ve used the pattern “[^ ]” instead of “\\S”. This is because we would like to replace non-space characters instead of just the non-whitespace characters.

值得一提的是,在String.replaceAll()调用中,我们使用了模式“[^ ]”而不是“\\S”。这是因为我们想替换非空格字符,而不仅仅是非空格字符。

3.5. Using the String.split() Method

3.5.使用String.split()方法

We’ve seen that the solution with the String.replaceAll() method is neat and compact. Now, let’s see another idea to solve the problem: using the String.split() method.

我们已经看到,用String.replaceAll()方法的解决方案是整洁而紧凑的。现在,让我们看看另一个解决问题的思路:使用String.split()方法。

As we know, we can pass a pattern to the String.split() method and get an array of strings that split by the pattern.

正如我们所知,我们可以向String.split()方法传递一个模式,并获得一个由该模式分割的字符串数组。

So, the idea is, we can split the input string by a single space. Then, the count of spaces in the original string will be one less than the string array length.

所以,我们的想法是,我们可以用一个空格来分割输入的字符串。然后,原始字符串中的空格数将比字符串阵列的长度少一个

Now, let’s see if this idea works:

现在,让我们看看这个想法是否可行。

@Test
void givenString_whenCountSpaceBySplit_thenReturnsExpectedCount() {
    int spaceCount = INPUT_STRING.split(" ").length - 1;
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

4. Using External Libraries

4.使用外部库

Apache Commons Lang 3 library is widely used in Java Projects. Also, Spring is a popular framework among Java enthusiasts.

Apache Commons Lang 3库被广泛用于Java项目中。另外,Spring是Java爱好者中流行的框架。

Both libraries have provided a handy string utility class.

这两个库都提供了一个方便的字符串实用类。

Now, let’s see how to count spaces in an input string using these libraries.

现在,让我们看看如何使用这些库来计算输入字符串中的空格。

4.1. Using the Apache Commons Lang 3 Library

4.1.使用Apache Commons Lang 3库

The Apache Commons Lang 3 library has provided a StringUtil class that contains many convenient string-related methods.

Apache Commons Lang 3库提供了一个StringUtil类,其中包含了许多与字符串相关的便利方法。

To count the spaces in a string, we can use the countMatches() method in this class.

要计算一个字符串中的空格,我们可以使用该类中的countMatches()方法。

Before we start using the StringUtil class, we should check if the library is in the classpath. We can add the dependency with the latest version in our pom.xml:

在我们开始使用StringUtil类之前,我们应该检查该库是否在classpath中。我们可以在pom.xml中用最新版本添加该依赖关系。

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

Now, let’s create a unit test to show how to use this method:

现在,让我们创建一个单元测试来展示如何使用这个方法。

@Test
void givenString_whenCountSpaceUsingApacheCommons_thenReturnsExpectedCount() {
    int spaceCount = StringUtils.countMatches(INPUT_STRING, " ");
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

4.2. Using Spring

4.2.使用Spring

Today, a lot of Java projects are based on the Spring framework. So, if we’re working with Spring, a nice string utility provided by Spring is already ready to use: StringUtils.

今天,很多Java项目都是基于Spring框架的。因此,如果我们正在使用Spring,Spring提供的一个不错的字符串工具已经可以使用了。StringUtils

Yes, it has the same name as the class in Apache Commons Lang 3. Moreover, it provides a countOccurrencesOf() method to count the occurrence of a character in a string.

是的,它与Apache Commons Lang 3中的类有相同的名字。此外,它还提供了一个countOccurrencesOf()方法来计算一个字符在字符串中的出现次数。

This is exactly what we’re looking for:

这正是我们正在寻找的。

@Test
void givenString_whenCountSpaceUsingSpring_thenReturnsExpectedCount() {
    int spaceCount = StringUtils.countOccurrencesOf(INPUT_STRING, " ");
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

5. Conclusion

5.总结

In this article, we’ve addressed different approaches to counting space characters in an input string.

在这篇文章中,我们已经讨论了计算输入字符串中空格字符的不同方法。

As always, the code for the article can be found over on GitHub.

一如既往,该文章的代码可以在GitHub上找到over