首页 > 试题广场 >

【编程】写入一个方法,输入一个文件名和一个字符串,统计这个字

[问答题]

【编程】写入一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。

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;
	}

}

发表于 2017-08-11 11:52:30 回复(2)
采用递归的方法,首先获取子串在原串中的首次出现的位置,然后截取掉子串,再从剩下的字符串中获取子串的位置,直到最后在剩下的字符串中找不到子串的位置,最后打印次数
发表于 2020-02-20 00:07:09 回复(0)
逐字符遍历,比较与字符串首字符是否相等,相等则比较下个字符,否则结束当前遍历,下个字符再从首字符开始,那些说用count和正则表达式的是认真的吗?算法题还能用高级函数的吗
发表于 2018-06-19 11:21:45 回复(0)
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;
	}

发表于 2017-08-29 11:49:32 回复(0)
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();
        }
    }
}

发表于 2020-03-21 12:37:45 回复(0)
        public static long CalculateStringCount(string fileName, string checkString)
        {
            long count = 0;
            var lines = File.ReadAllLines(fileName);
            foreach (var line in lines)
            {
                count += line.Split(' ').Count(t => t.ToString() == checkString);
            }
            return count;
        }
发表于 2019-10-09 17:46:32 回复(0)
直接split(  这个字符串  ) 然后输出数组的length-1,就是出现的次数吧
编辑于 2019-08-17 19:17:48 回复(0)
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;
        }
    }
   
}


发表于 2019-06-22 10:28:17 回复(0)
用正则中的findall,然后列表长度就是字符串出现的次数,前面的都是些啥呀,太复杂了,根本看不懂
编辑于 2018-11-05 17:25:42 回复(0)
我觉得用正则表达式全局查找匹配效率会更高一些!
发表于 2018-02-12 16:43:13 回复(0)
使用map<string,integer>开始,如果找不到键,value设为1. 之后每次查找,使用map.put覆盖原value值。
发表于 2017-08-11 17:40:19 回复(0)
发表于 2017-08-11 11:08:06 回复(0)
/**
 * 编程】写入一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;


public class Test {

public static void main(String[] args) throws IOException {
String str_match = "abcd";
Path path = FileSystems.getDefault().getPath("F:/123.txt");
InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
BufferedReader br = Files.newBufferedReader(path);
String line = br.readLine();
int count = 0;
while (line != null) {
for(int i = 0; i<line.length(); i++) {
int k = 0;
for(;k<str_match.length();k++) {
if (line.charAt(i+k)!=str_match.charAt(k)) break;
}
if(k==str_match.length())count++;
}
line = br.readLine();
}
System.out.println(count);
}

}
发表于 2017-08-10 21:26:32 回复(1)
首先建一个file类判断文件是否存在,若存在用inputreade每次读取一行字符串,再以空格逗号句号等为分界点,利用squrt函数分割成字符串数组,与此字符串比较,记录相同个数,依次类推查找整个文件
发表于 2017-08-10 07:24:03 回复(0)
用正则全局搜索字符,返回次数; 用indexof查找,查找到删除,并创建临时变量自增,再次查找。
发表于 2017-08-09 19:37:25 回复(0)