gpt4 book ai didi

java - 使用 map 计算文本文件中出现的次数

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:39:32 24 4
gpt4 key购买 nike

下面的代码将计算每个字符的出现次数。如果我在文本文件中有 abc 输出将是 1 b 1 c 1。我在许多网站上读到 for 循环将花费很多时间,最好使用 HashMap 实现相同的循环。你们中的任何人都可以帮助我如何转换这个实现 HashMap 的程序吗?

 import java.io.*;

class Count_Char {
public static void main(String[] args) {
try
{
FileInputStream file = new FileInputStream("D:\\trial.txt");
DataInputStream dis = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String Contents="";
String str="";
while ((Contents = br.readLine()) != null) {
str+=Contents;
}
char[]char_array =str.toCharArray();
for(int count =0;count<char_array.length;count++){
char ch= char_array[count];
int counter=0;
for ( int i=0; i<char_array.length; i++){
if (ch==char_array[i])
counter++;
}
boolean flag=false;
int j=count-1;
while(j>=0)
{

if(ch==char_array[j])
flag=true;
j--;
}
if(!flag){
System.out.println(ch+" "+counter);
}
}
}catch(IOException e1){
System.out.println(e1);
}
}
}

最佳答案

快速伪代码。基本上,这里的技巧是将字符保存为 Map 中的键,并将值保存为该字符(键/值对)的出现次数。

 //declare a map to hold your characters and their counters
Map<String,Integer> charCounter = new HashMap<String,Integer>();
//the following if else logic goes when you are looping through your tokens
if(charCounter.containsKey(<your character>)){
charCounter.put(<your character>,charCounter.get(<your character>)+1);
}else{
charCounter.put(<your character>,1);
}

遍历完成后,可以这样打印 map 。

for(String key : charCounter.keySet()) {
System.out.println(key+" "+charCounter.get(key));
}

关于java - 使用 map 计算文本文件中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4363061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com