阅读文本文件,并存储每个单个字符发生 [英] Read a text file and store every single character occurrence
问题描述
我想作一个java程序来读取一个文本文件,并存储每个单个字符发生。因此,这将占到标点符号,字母,数字,大写,小写等。
给定一个文本文件,如:
I would like to make a java program that will read a text file and store every single character occurrence. So it will account for punctuation, letters, numbers,uppercase, lowercase ect. Given a text file like:
玫瑰是红色的,
紫罗兰是蓝色的。
打印值将是这样的:
R:1。
R:3
我:1
,1
[等]
到目前为止,我能够读取文件并计算字数,行数,字符。
So far I am able to read a file and count words, lines, chars.
package Exercise3;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
public class StringTokenizerDemo1
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
File file = new File("C://Users//guy//Desktop//Practice.txt");
Scanner inputFile = new Scanner(file);
String line, word;
StringTokenizer token;
int words = 0; //word count
int lines = 0; //line count
int chars = 0; //char count
while (inputFile.hasNext())
{
lines++; //add one to line count
line = inputFile.nextLine();
token = new StringTokenizer(line, " ");
while (token.hasMoreTokens())
{
words++; //add one word count
word = token.nextToken();
chars+= word.length(); //add to char count
}
}
}
}
我还没学会哈希映射/表或树状图;寻找有关如何存储使用数组,数组列表或LinkedList的所有字符类型和它们要么出现一些建议。
I have not learned hash maps/tables or treemaps; looking for some advice on how to store all char types and their occurrences either using an array,arraylist or linkedlist.
推荐答案
这将统计每个字符的出现在一个数组结果
公共类爵士{
This will count the occurrences of each character in an array
public class jazz {
public static void main(String[] args) {
String [] arr = {"a", "b", "a","c", "d"};
HashMap<String, Integer> map = new HashMap<String,Integer>();
for (String i : arr) {
if (map.get(i) == null) {
map.put(i, 1);
} else {
map.put(i, map.get(i) + 1);
}
}
这篇关于阅读文本文件,并存储每个单个字符发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!