java統計字符串中指定元素湧現次數辦法。本站提示廣大學習愛好者:(java統計字符串中指定元素湧現次數辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java統計字符串中指定元素湧現次數辦法正文
本文實例講授了統計文本中某個字符串湧現的次數或字符串中指定元素湧現的次數辦法,分享給年夜家供年夜家參考,詳細內容以下
運轉後果圖:
法式查找的上此文件帶"a"的字符在若干次
詳細代碼以下
package com.zuidaima.util.string;
import java.io.*;
public class CountString {
public static int count(String filename, String target)
throws FileNotFoundException, IOException {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
StringBuilder strb = new StringBuilder();
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
strb.append(line);
}
String result = strb.toString();
int count = 0;
int index = 0;
while (true) {
index = result.indexOf(target, index + 1);
if (index > 0) {
count++;
} else {
break;
}
}
br.close();
return count;
}
public static void main(String[] args) {
try {
System.out.println(count("D:\\zuidaima.txt", "a"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是java統計字符串中指定元素湧現次數辦法,願望對年夜家的進修有所贊助。