标签:count String 文件名 一个 int length 字符串 new bis
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+"次";
}
}
标签:count,String,文件名,一个,int,length,字符串,new,bis 来源: https://www.cnblogs.com/xiaocheng228/p/14654876.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。