首页 > 其他 > 详细

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

时间:2021-04-13 23:14:12      阅读:21      评论:0      收藏:0      [点我收藏+]
import java.io.*;

/**
 * 写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数
 */
public class SumString {
    public static void main(String[] args) {

        System.out.println(sumString01(new File("d:/a.txt"), "100"));
        System.out.println(sumString02(new File("d:/a.txt"), "100"));

    }

    //方法一:
    static String sumString01(File file,String str){
        BufferedInputStream bis = null;
        int count = 0;
        try {
            bis = new BufferedInputStream(new FileInputStream(file.getPath()));
            int temp = 0;
            StringBuffer sb = new StringBuffer();
            while ((temp = bis.read())!=-1){
                sb.append((char)temp);
            }
            String s = sb.toString();
            int index = 0;

            while ((index = s.indexOf(str,index)) != -1)
            {
                count++;
                System.out.println("第"+count+"次;索引是" + index);
                index = index + str.length();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "字符串出现共:"+count+"次";
    }

    //方法二:
    static String sumString02(File file,String str){
        BufferedInputStream bis = null;
        int count = 0;
        try {
            bis = new BufferedInputStream(new FileInputStream(file.getPath()));
            int temp = 0;
            StringBuffer sb = new StringBuffer();
            while ((temp = bis.read())!=-1){
                sb.append((char)temp);
            }
            String s1 = sb.toString();
            String s2 = "";

            int length = s1.split(str).length;
            //判断文件末尾是否包含字符子串
            if(s1.substring(s1.length()-3,s1.length()).contains(str)){
                count=length;
            }else {
                count=length-1;
            }
            

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "字符串出现共:"+count+"次";
    }
}

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

原文:https://www.cnblogs.com/xiaocheng228/p/14654876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!