统计字符串中每个字符出现的次数

时间:2025-02-18 15:11:55

1.概述
有很多方法可以计算Java中字符串中 char 的出现次数。

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

2.使用Core Java Lib
2 .1。命令式方法
一些开发人员可能更喜欢使用核心 Java。有很多方法可以计算字符串中 char 的出现次数。

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

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

毫不奇怪,这会起作用,但是有更好的方法可以做到这一点。

2.2. 使用递归

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

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

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

2.3. 使用正则表达式

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

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

请注意,此解决方案在技术上是正确的,但不是最佳的,因为使用非常强大的正则表达式来解决诸如查找字符串中字符出现次数这样的简单问题是多余的。

2.4. 使用 Java 8 功能

Java 8 中可用的新特性在这里非常有用。

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

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

因此,这显然是一个使用核心库的更清洁、更易读的解决方案。

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

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

首先,我们需要包含适当的依赖项:
<dependency>
    <groupId></groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

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

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

3.2. 使用Guava
番石榴也有助于计算字符。我们需要定义依赖:

<dependency>
    <groupId></groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

让我们看看 Guava 如何快速帮助我们计算字符:

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

3.3. 使用Spring

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

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

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

1、方法一:字符串的原始操作

   public static void main(String [] sgrs){
       /**
        * 如:"1王235868asda17394利3@@89我0我2342";统计出每个字符出现的次数。
        */
       String str="1王235868asda17394利3@@89我0我2342";
       int[] count=new int[()];//每个字符出现的次数
       String b=new String();//存储去除重复之后的字符串
       for(int i=0;i<();i++){
            if(!(((i)))){
                b+=((i));
            }
            else{
                for(int j=0;j<();j++){
                        if((i)==(j)){
                            count[j]++;
                    }
                }
            }
        }
       ("原字符串str:");
       (str);
       //(b);
       for(int i=0;i<();i++){
            ((i)+":出现的次数:"+(count[i]+1));
       }
   }

2、方式二、利用Map数据结构

	public static void main(String[] args) {
        /**
         * 如:"1王235868asda17394利3@@89我0我2342";统计出每个字符出现的次数。
         */
        String str = "1王235868asda17394利3@@89我0我2342";
        char[] chars = ();
        Map<Character, Integer> map = new HashMap();
        for (char c : chars) {
            if ((c)) {
                (c, (c) + 1);
            }else{
                (c,1);
            }
        }
        for (<Character, Integer> entry : ()) {
            ("字符("+()+")出现的次数为:"+());
        }
    }