使用地图计算文本文件中出现的次数
下面的代码将计算每个字符的出现次数。如果我在文本文件中有 abc 输出将是 a 1 b 1 c 1。我在许多网站上读到 for 循环将花费大量时间,最好使用哈希映射来实现相同的效果。你们中的任何人都可以帮我如何转换这个实现哈希映射的程序吗?
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);
}
}
}
The code below will count the occurences of every character. If i have abc in the text file output would be a 1 b 1 c 1. I read in many sites that for loop will be taking much of time and it is better to implement the same using hash map. Can any of you help me how to convert this program implementing hash map?
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
快速伪代码。基本上,这里的技巧是将字符保存为映射中的键,值是该字符出现的次数(键/值对)。
遍历完成后,您可以通过这种方式打印地图。
Quick pseudo code. Basically the trick here is that you save the characters as keys in the Map and the value being the count of the occurrences for that character (key/value pair).
After you are done traversing, you can print the map this way.
FileInputStream 文件 = new FileInputStream("");
DataInputStream dis = new DataInputStream(文件);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
建立在逻辑上,coolbean 已经写好了..希望这会有所帮助...我已经测试过这个..
FileInputStream file = new FileInputStream("");
DataInputStream dis = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
build on logic coolbean gave hav writtn it ..Hope this will help... I have tested this..