import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CountStringTest {
public static void main(String[] args) {
try {
System.out.println("C盘下面 面试题.docx中的q字符出现的次数为:");
System.err.println(count("C:\\Users\\MC--小驰\\Desktop\\精粹\\面试题.docx", "q"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
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;
}
}
读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数
最新推荐文章于 2020-04-23 17:05:45 发布