java中给定字符串的线性搜索?有没有更好的解决办法?
对不起,如果我的问题很傻,但我需要一些帮助。 好吧,问题是我正在努力学习java,并试图制作一个小程序 它将在文本文件中搜索已插入的匹配字符串 参数我想知道我应该修复程序的哪一部分以使该方法正常工作,或者至少想知道是否有更好的解决方案
public String linaerSearch(String filename,String strToArrays){
String[]arrays;
File f = new File("C:\\Users\\toyman\\Documents\\NetBeansProjects\\ToyMaker\\"+filename);
String[]items = (strToArrays.split("\\s*,\\s*"));//converting the string into arrays by comma
//convert the int into string
StringBuilder build = new StringBuilder();
if(f.exists()){ //checks if the file actually exists
try(FileInputStream fis = new FileInputStream(f)){
int con; int incrementor =0;
while((con=fis.read())!=-1){
incrementor++;
char str = (char)con;
String str2 = Character.toString(str);
if(items[ ????? ].equals(str2)){
// I want to check if the string that has been passed in the parameter
// exists in the file. But I got confused at the items[ ???? ].
System.out.println("found you");
}
//System.out.println();
//convert to char and display it
System.out.print(str2);
}
}catch(Exception e){
e.printStackTrace();
}
}else{
System.out.println("The file doesn't exist. Create a new file or use a existing file");
}
return "";
}
# 1 楼答案
如果您想在文本中搜索某个字符串,并正确地执行它,那么它与Java无关。你要找的是一个字符串搜索算法
试试看维基百科:http://en.wikipedia.org/wiki/String_searching_algorithm
我建议你选择其中一种:
它们都是非常好且高效的算法,而且都相当容易实现