我想从文本文件中搜索字符存在的时间。例如,一个文本文件包含
a bbb a abab bnbn
我只想读a而不是a。我希望结果是:
a = 2
private void compute3() {
String[] reservedWord = new String[] {"a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C",
"D", "E", "F", "G", "X", "Y", "Z"};
ArrayList<String> cntStr = new ArrayList<String>();
int cnt=0;
int cnt3=0;
try {
FileInputStream fis = new FileInputStream(chooser.getSelectedFile());
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while(br.ready()){
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
while(st.hasMoreTokens()){
String txt = st.nextToken();
for(cnt = 0;cnt<reservedWord.length;cnt++){
if(txt.contains(reservedWord[cnt])){
cntStr.add(reservedWord[cnt]);
}
}
}
}
br.close();
int cnt2;
ArrayList<String> counterPerWord = new ArrayList<String>();
int counter = 0;
for(cnt = 0;cnt<reservedWord.length;cnt++){
counter = 0;
for(cnt2 = 0;cnt2<cntStr.size();cnt2++){
if(reservedWord[cnt].equals(cntStr.get(cnt2))){
counter++;
}
}
//counter which is int becomes String
counterPerWord.add(counter + "");
}
cnt = 0;
int N2 = 0;
int n2 = 0;
while(cnt!=counterPerWord.size()){
jTextArea6.append(reservedWord[cnt] + " = " + counterPerWord.get(cnt) + "\n");
System.out.println(reservedWord[cnt] + " = " + counterPerWord.get(cnt));
N2 = N2 + Integer.parseInt(counterPerWord.get(cnt));
cnt++;
}
if(n2 >= 1){
n2++;
}
//N1 = N1 * 2;
jTextField7.setText("" + N2 + "");
System.out.println("N2: " + N2);
System.out.println("");
jTextField5.setText("" + n2 + "");
//System.out.println("n1:" + n1);
} catch (Exception e) {
e.printStackTrace();
}}
它还从单词中获取其他字符。