首页 > 其他 > 详细

统计一个字符串在文本文件中的出现次数

时间:2017-11-09 21:35:51      阅读:168      评论:0      收藏:0      [点我收藏+]

代码实现:

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次

  

统计一个字符串在文本文件中的出现次数

原文:http://www.cnblogs.com/mlan/p/7811382.html

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