小豪呵呵
2015-12-04 09:40
如何编写记录一个文档中某个字数出现的次数
public static void main(String[] args) { print("d:/test.txt","b"); } public static void print(String fileName,String str){ try { FileInputStream inputStream = new FileInputStream(fileName); InputStreamReader reader = new InputStreamReader(inputStream); StringBuffer sb = new StringBuffer(); while(reader.ready()){ sb.append((char)reader.read()); } int count = 0; int fromIndex =0; while(true){ fromIndex=sb.indexOf(str, fromIndex); if(fromIndex!=-1){ fromIndex++; count++; }else{ break; } } System.out.println(sb.toString()); System.out.println(count); reader.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/* * 读取一个文档里的一个字符出现的次数 */ public static void print(String fileName,String str){ try { // 构建FileInputStream对象 FileInputStream inputStream = new FileInputStream(fileName); // 构建InputStreamReader对象,可以指定编码格式 InputStreamReader reader = new InputStreamReader(inputStream); StringBuffer sb = new StringBuffer(); while(reader.ready()){ sb.append((char)reader.read());// 转成char加到StringBuffer对象中 } int count = 0;//出现的次数 int fromIndex =0;//indexOf中查询参数 while(true){ fromIndex=sb.indexOf(str, fromIndex);//返回该字符在文档中出现的位置,int if(fromIndex!=-1){ //找到了该字符,查询的索引+1,出现的次数+1 fromIndex++; count++; }else{ break; } } System.out.println(sb.toString()); System.out.println(count); reader.close();// 关闭读取流 inputStream.close();// 关闭输入流,释放系统资源 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
System.out.println(new CharCounter().counter("LOVELOVEYOU",'O'));//这一行是什么意思?
public class CharCounter{
public static int counter(String s,char c){
int count=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)==c){
count++;
}
}
return count;
}
public static void main(String args[]){
System.out.println(new CharCounter().counter("LOVELOVEYOU",'O'));
}
}
Java入门第二季 升级版
530656 学习 · 6091 问题
相似问题