日期:2014-05-20  浏览次数:20748 次

大家来讨论下这个面试题
写一个程序,从文件(c:\test.txt)中查出字符串”zhuobin”出现的次数?
  (要求:用最简洁的方法,写出符合上面要求的程序)

------解决方案--------------------
String类的indexOf递归遍历就可以实现 我觉得 不过效率就不是很好了
------解决方案--------------------
public int findNumOfStringInFile(String filePath,String str)throws Exception{
BufferReader br = new BufferReader(new FileReader(new File(filePath)));
String line = null;
int num = 0;
while(line=br.readLine()!=null){
String[] s = line.split(str);
if(s.length()>1)
num+=s.length-1;
}
return num;
}

------解决方案--------------------
探讨
public int findNumOfStringInFile(String filePath,String str)throws Exception{
BufferReader br = new BufferReader(new FileReader(new File(filePath)));
String line = null;
int num = 0;
while(line=br.readLine()!=null){
String[] s = line.split(str);
if(s.length()>1)
num+=s.length-1;
}
return num;
}

------解决方案--------------------
不会写
------解决方案--------------------
BufferedReader in = new BufferedReader(new FileReader("c:\\test.txt"));
String s = "";
int num = 0;
while ((s = in.readLine()) != null) {
if (line.indexOf("zhuobin") > 0) ++num;
}

return num;

------解决方案--------------------
探讨
public int findNumOfStringInFile(String filePath,String str)throws Exception{
BufferReader br = new BufferReader(new FileReader(new File(filePath)));
String line = null;
int num = 0;
while(line=br.readLine()!=null){
String[] s = line.split(str);
if(s.length()>1)
num+=s.length-1;
}
return num;
}


------解决方案--------------------
探讨
万一那个单词换行了怎么办?

------解决方案--------------------
探讨
BufferedReader in = new BufferedReader(new FileReader("c:\\test.txt"));
String s = "";
int num = 0;
while ((s = in.readLine()) != null) {
if (line.indexOf("zhuobin") > 0) ++num;
}

return num;

------解决方案--------------------
同上,如果是查"zhuobin"的词的话,就不能用indexof 了.可能会有"sb_zhuobin"这样的存在
------解决方案--------------------
不追求效率的话 indexof可以·


------解决方案--------------------
探讨
引用:
public int findNumOfStringInFile(String filePath,String str)throws Exception{
BufferReader br = new BufferReader(new FileReader(new File(filePath)));
String line = null;
int num = 0;
while(line=br.readLine()!=null){
String[] s = line.split(str);
if(s.length()>1)
num+=s.length-1;
}
return num;
}

这个没创意  哈哈哈哈

------解决方案--------------------
探讨
引用:
引用:
public int findNumOfStringInFile(String filePath,String str)throws Exception{
BufferReader br = new BufferReader(new FileReader(new File(filePath)));