zoukankan      html  css  js  c++  java
  • 统计一个字符串在文本文件中的出现次数

    代码实现:

    package com.jn.test;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.Scanner;
    
    public class StringTimes {
    	 public static int getKeyStringCount(String str, String key) {          
             int count = 0;  
             int index = 0;             
             while((index = str.indexOf(key,index))!=-1){                 
                 index = index + key.length();  
                 count++;                 
             }              
             return count;  
         }  
        
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		File file = new File("D:/设计模式.txt");
    		FileInputStream fis = null;
    		try{
    			fis = new FileInputStream(file);
    			int len = 0;
    			byte[] buf = new byte[1024];
    			String str = null;
    			while((len = fis.read(buf)) !=-1){
    				str = new String(buf, 0, len,"GBK");			
    			}
    			Scanner sc  = new Scanner(System.in);
    			System.out.println("请输入你要查询字符串:");
    			 String key = sc.nextLine();  
                 int count = getKeyStringCount(str,key);  
                 System.out.println("文件中此字符串出现次数为:"+count+"次");  
    		}catch(FileNotFoundException e){
    			e.printStackTrace();
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally{
    			try {
    				fis.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	}
    }
    

      运行及结果:

    请输入你要查询字符串:
    设计模式
    文件中此字符串出现次数为:10次
    

      

  • 相关阅读:
    我所理解的NAT
    H3C防火墙安全策略故障排查思路
    职场建议
    小型企业典型网络内部拓扑
    echo&printf
    笔挺站立 昂首挺胸
    Jordan Peterson 的建议
    刚才思考的两个问题
    高手的见解
    一个企业网络管理人员的注意事项
  • 原文地址:https://www.cnblogs.com/mlan/p/7811382.html
Copyright © 2011-2022 走看看