1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java统计文件中字符串出现的次数_统计一个字符串在文本文件中的出现次数

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

时间:2021-03-05 15:43:34

相关推荐

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次

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。