【编程】写入一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Main{ /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String fileName = "aaa.txt"; String str = "ab"; int num = Count(fileName, str); System.out.println(num); } public static int Count(String fileName , String str) throws Exception{ //获取文件中的字符 FileReader fr = new FileReader(new File(fileName)); BufferedReader br = new BufferedReader(fr); StringBuffer sb = new StringBuffer(); String line; while((line = br.readLine()) != null ){ sb.append(line); } String filestr = sb.toString(); //文件中的字符 System.out.println(filestr); //统计这个字符串在这个文件中出现的次数 int num = 0; while(filestr.length() > str.length()){ int index = filestr.indexOf(str); if(index>-1){ //存在字符串str num++; filestr = filestr.substring(index+str.length()); } else{ break; } } return num; } }
public static int fun(File file,String s){ int count=0; String read; String readAll = ""; int i=0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); while((read = br.readLine())!=null){ readAll += read; } while(readAll.indexOf(s,i)!=-1){ i=readAll.indexOf(s,i)+s.length(); count++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return count; }
import java.io.File; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String filename,str; if(scan.hasNextLine()){ filename = scan.nextLine(); }else { return; } if (scan.hasNextLine()){ str = scan.nextLine(); }else { return; } File file = new File(filename); try { Scanner filereader = new Scanner(file); int num = 0; while (filereader.hasNextLine()){ String test = filereader.nextLine(); // System.out.println(test); Pattern patt = Pattern.compile(str); Matcher matcher = patt.matcher(test); while (matcher.find()){ num++; } } System.out.println(num); }catch (Exception ex){ ex.printStackTrace(); } } }
using System; using System.Diagnostics; using System.IO; using System.Threading; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string fileName = @"D:\temp\a.txt"; string testStr = "ab"; Console.WriteLine("文件中包含{0}字符{1}个", testStr, ReadStringCount(fileName, testStr)); Console.ReadKey(); } static int ReadStringCount(string fileName,string str) { int totalCount = 0; string[] strs1 = File.ReadAllLines(fileName); for (int i = 0; i < strs1.Length; i++) { string tempStr = strs1[i]; while (tempStr.IndexOf(str) != -1) { int tempInx = tempStr.IndexOf(str); totalCount++; tempStr = tempStr.Substring(tempInx + str.Length); } } return totalCount; } } }