package com.xjh.demo.exam; import java.io.*; /** * 给定一个txt文件,如何得到某字符串出现的次数 */ public class StringCount { public static void main(String[] args) { String filePath = "D:\\a.txt"; File file = new File(filePath); try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK")); String temp = null; String result = ""; while ((temp = bufferedReader.readLine()) != null) { result += temp; } bufferedReader.close(); System.out.println(result); int index = 0; int count = 0; String specialStr = "d"; int len = specialStr.length(); while ((index=result.indexOf(specialStr, index)) != -1) { index += len; count++; } System.out.println(count); } catch (Exception e) { e.printStackTrace(); } } }
读取txt文件,获取指定字符串出现的次数
最新推荐文章于 2021-03-11 10:21:25 发布