如何统计字符串中字符的出现频率?

36

我需要写一个循环来统计字符串中每个字母的出现频率。
例如:"aasjjikkk" 将会有 2 个 'a',1 个 's',2 个 'j',1 个 'i',3 个 'k'。最终,我希望这些数据以字母为键、出现次数为值的形式被存储在一个 map 中。有好的想法如何实现吗?


你可以在这个重复的问题上找到更多好的答案:如何将字符流转换为Map<Character, Integer> - undefined
27个回答

0

如果不需要超级快速,只需创建一个整数数组,每个字母对应一个整数(仅限字母,因此是2*26个整数?或任何二进制数据可能?)。逐个字符遍历字符串,获取相应整数的索引(例如,如果您只有字母字符,可以将“ A”放在索引0处,并通过将任何“A”到“ Z”减去“A”来获取该索引,这只是一个示例,说明如何获得相当快的索引),并增加该索引中的值。

有各种微小的优化可使其更快(如果必要)。


0
*import java.util.ArrayList;
import java.util.Collections;

public class Freq {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String temp="zsaaqaaaaaaaabbbbbcc";
    List<String> temp1= new ArrayList<String> ();
    ArrayList<Integer>freq=new ArrayList<Integer>();
    for(int i=0;i<temp.length()-1;i++)
    {       
        temp1.add(Character.toString(temp.charAt(i)));      
    }
    Set<String> uniqset=new HashSet<String>(temp1);
    for(String s:uniqset)
    {
        freq.add(Collections.frequency(temp1, s));
        System.out.println(s+" -->>"+Collections.frequency(temp1, s));
    }
    }

}
           ------Output-------
       a -->>10
       b -->>5
       c -->>1
       q -->>1
       s -->>1
       z -->>1

使用集合的 frequency 方法来计算 char* 的频率。

0

这是一种更有效的方法来统计字符串中字符的频率

public class demo {
    public static void main(String[] args) {
        String s = "babdcwertyuiuygf";
        Map<Character, Integer> map = new TreeMap<>();
        s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));
        StringBuffer myValue = new StringBuffer();
        String myMapKeyValue = "";
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            myMapKeyValue = Character.toString(entry.getKey()).concat(
                Integer.toString(entry.getValue()));
            myValue.append(myMapKeyValue);
        }
        System.out.println(myValue);
    }
}

0
package com.dipu.string;

import java.util.HashMap;
import java.util.Map;

public class RepetativeCharInString {
    public static void main(String[] args) {
        String data = "aaabbbcccdddffffrss";
        char[] charArray = data.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char c : charArray) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        System.out.println(map);

    }
}

2
请记得始终添加代码的解释。 - mypetlion

0
我们可以使用Collections类的频率方法来实现这一功能。将字符串拆分为字符串数组。使用HashSet去除重复项,并使用Collections的frequency方法检查HashSet中每个对象的频率。
void usingCollections(){

  String input = "cuttack";

  String [] stringArray = input.split("");

  Set<String> s = new HashSet(Arrays.asList(stringArray));

  for(String abc : s){

    System.out.println (abc + ":"+Collections.frequency(Arrays.asList(stringArray),abc));

  }
}

1
尽管此代码可能解决了问题,但加上解释(//meta.stackexchange.com/q/114762)说明如何以及为什么解决问题将有助于改善您的帖子质量,可能会导致更多的赞同。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请[编辑]您的答案以添加解释并指出适用的限制和假设。 - Dharman

-1
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Iterator;
public class CountFrequencyOfCharater {
public static void main(String args[]) throws Exception
{
    HashSet hs=new HashSet();
    String str="hey how are you?";
    char arr[]=new char[str.length()];
    for(int i=0;i<str.length();i++)
    {
        arr[i]=str.charAt(i);
    }
    for(int j=0;j<str.length();j++)
    {
        int c=0;
        for(int k=0;k<str.length();k++)
        {
            if(arr[j]==arr[k])
            c++;
        }
        hs.add(arr[j]+"="+c+",");
    }
        Iterator it=hs.iterator();
        while(it.hasNext())
        {
             System.out.print(it.next());
        }
  }
}

1
请添加一些描述或解释,说明为什么这段代码有效,而不仅仅提供代码。这将使未来查看它的人更有意义。 - Aelphaeis

-3

#来自 C 语言

 #include<stdio.h>`
 #include <string.h>`
  int main()
{
    char s[1000];  
    int  i,j,k,count=0,n;
    printf("Enter  the string : ");
    gets(s);
    for(j=0;s[j];j++);
    n=j; 
    printf(" frequency count character in string:\n");
    for(i=0;i<n;i++)  
    {
        count=1;
        if(s[i])
        {
        
          for(j=i+1;j<n;j++)  
          {   
            
            if(s[i]==s[j])
            {
                 count++;
                 s[j]='\0';
            }
          }  
          printf(" '%c' = %d \n",s[i],count);
       }
    } 
    return 0;
}

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - adiga
1
只是好奇,为什么你会用不同的编程语言回答一个标记为Java的问题呢? - luckyguy73

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接