Count Occurrences of a Char in a String – 计算字符串中一个字符的出现次数

最后修改: 2017年 5月 14日

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

1. Overview

1.概述

There are many ways to count the number of occurrences of a char in a String in Java.

在Java中,有许多方法来计算一个char在String中出现的次数。

In this quick tutorial, we’ll focus on a few examples of how to count characters — first with the core Java library and then with other libraries and frameworks such as Spring and Guava.

在这个快速教程中,我们将重点介绍几个如何计算字符的例子–首先是使用核心Java库,然后是使用其他库和框架,如Spring和Guava。

2. Using Core Java Lib

2.使用Core Java Lib

2.1. Imperative Approach

2.1.强制性的方法

Some developers may prefer to use core Java. There are many ways for counting the number of occurrences of a char in a String.

有些开发者可能更喜欢使用核心Java。有很多方法可以计算字符串中一个字符的出现次数。

Let’s start with a simple/naive approach:

让我们从一个简单/天真的方法开始。

String someString = "elephant";
char someChar = 'e';
int count = 0;
 
for (int i = 0; i < someString.length(); i++) {
    if (someString.charAt(i) == someChar) {
        count++;
    }
}
assertEquals(2, count);

Not surprisingly, this will work, but there are better ways to do this.

毫不奇怪,这将会起作用,但有更好的方法来做这件事。

2.2. Using Recursion

2.2.使用递归

A less obvious but still interesting solution is to use recursion:

一个不太明显但仍然有趣的解决方案是使用递归。

private static int countOccurences(
  String someString, char searchedChar, int index) {
    if (index >= someString.length()) {
        return 0;
    }
    
    int count = someString.charAt(index) == searchedChar ? 1 : 0;
    return count + countOccurences(
      someString, searchedChar, index + 1);
}

We can invoke this recursive method in the following way: useRecursionToCountChars(“elephant”, ‘e’, 0).

我们可以通过以下方式调用这个递归方法。useRecursionToCountChars(“elephant”, ‘e’, 0)

2.3. Using Regular Expressions

2.3.使用正则表达式

Another way would be to use regular expressions:

另一种方法是使用正则表达式。

Pattern pattern = Pattern.compile("[^e]*e");
Matcher matcher = pattern.matcher("elephant");
int count = 0;
while (matcher.find()) {
    count++;
}
 
assertEquals(2, count);

Just note that this solution is technically correct but sub-optimal, as it’s overkill to use the very powerful regular expressions to solve such a simple problem as finding the number of occurrences of a character in a string.

请注意,这种解决方案在技术上是正确的,但却是次优的,因为使用非常强大的正则表达式来解决寻找字符串中一个字符的出现次数这样一个简单的问题是矫枉过正。

2.4. Using Java 8 Features

2.4.使用Java 8的功能

New features available in Java 8 can be very helpful here.

Java 8中的新功能在这里可以发挥很大的作用。

Let’s use streams and lambdas to implement the count:

让我们使用流和lambdas来实现计数。

String someString = "elephant";
long count = someString.chars().filter(ch -> ch == 'e').count();
assertEquals(2, count);

long count2 = someString.codePoints().filter(ch -> ch == 'e').count();
assertEquals(2, count2);

So, this is clearly a cleaner and more readable solution using the core library.

所以,这显然是一个使用核心库的更干净、更可读的解决方案。

3. Using External Libraries

3.使用外部库

Let’s now look at a few solutions that make use of utilities from external libraries.

现在让我们来看看一些利用外部库的实用程序的解决方案。

3.1. Using StringUtils

3.1.使用 StringUtils

In general, it is always better to use an existing solution instead of inventing our own. The commons.lang.StringUtils class provides us with the countMatches() method, which can be used for counting chars or even sub-strings in given String.

一般来说,使用现有的解决方案总是比自己发明的要好。commons.lang.StringUtils类为我们提供了countMatches()方法,它可以用来计算给定String中的字符甚至是子字符串。

First, we need to include the appropriate dependency:

首先,我们需要包括适当的依赖关系。

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

We can find the latest version on Maven Central.

我们可以在Maven Central上找到最新版本。

Let’s now use countMatches() to count the number of e characters in the “elephant” String literal:

现在让我们使用countMatches()来计算 “elephant “字符串字面中e字符的数量。

int count = StringUtils.countMatches("elephant", "e");
assertEquals(2, count);

3.2. Using Guava

3.2.使用Guava

Guava can also be helpful in counting chars. We need to define the dependency:

Guava也可以在计算字符方面有所帮助。我们需要定义依赖关系。

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

We can find the latest version on Maven Central.

我们可以在Maven Central上找到最新版本。

Let’s see how Guava can quickly help us to count chars:

让我们看看Guava是如何快速帮助我们计算字符的。

int count = CharMatcher.is('e').countIn("elephant");
assertEquals(2, count);

3.3. Using Spring

3.3.使用Spring

Naturally, adding the Spring Framework into our project just to count chars doesn’t make sense.

自然,在我们的项目中加入Spring框架只是为了计算字符,这没有意义。

However, if we already have it in our project, we just need to use the countOccurencesOf() method:

然而,如果我们的项目中已经有了它,我们只需要使用countOccurencesOf()方法。

int count = StringUtils.countOccurrencesOf("elephant", "e");
assertEquals(2, count);

4. Conclusion

4.结论

In this article, we focused on various ways to count chars in the String. Some of them were designed purely in Java; some required additional libraries.

在这篇文章中,我们着重介绍了计算字符串中的字符的各种方法。其中有些是纯粹用Java设计的;有些需要额外的库。

Our recommendation is to use already existing utilities from StringUtils, Guava or Spring. However, this article offers some possibilities to get it done with Java 8 if using only plain Java is preferred.

我们的建议是使用StringUtils、Guava或Spring中已有的工具。然而,如果只想使用普通的Java,本文提供了一些用Java 8完成的可能性。

The complete source code for these examples is available in this GitHub project.

这些例子的完整源代码可在这个GitHub项目中找到。