日期:2014-05-20 浏览次数:21113 次
String str="asdfcomasdf";//读取com后面的字符串
str=str.subString(str.indexOf("com"),str.length());
------解决方案--------------------
String str="hello world,world peace,world";//读取com后面的字符串
String key = "world";
int pos = -key.length();
while((pos=str.indexOf("world", pos+key.length())) != -1){
if(pos+key.length()<str.length())
System.out.println(str.charAt(pos+key.length()));
else if(pos+key.length()==str.length())
System.out.println("文件尾");
}
------解决方案--------------------
public class Test {
public static void main(String[] args) throws IOException {
File file = new File("1.txt");
FileReader fr = new FileReader(file);
char buf;
boolean locate = false;
String match = "world";
char[] pattern = match.toCharArray();
StringBuilder sb = new StringBuilder();
while(fr.ready()) {
buf = (char)fr.read();
if(!locate && buf == pattern[0]) {
locate = testChar(buf,fr, pattern,0);
if(fr.ready())
buf = (char)fr.read();
else
break;
}
if(locate)
sb.append(buf);
}
System.out.println(sb.toString());
fr.close();
}
public static boolean testChar(char now,FileReader fr,char[] pattern,int pos) throws IOException {
if(pos == pattern.length - 1)
return true;
if(fr.ready()) {
if(now == pattern[pos])
return testChar((char)fr.read(),fr, pattern, pos+1);
else
return false;
} else {
return false;
}
}
}
------解决方案--------------------
自己玩的话
一行一行indexof就行了
考虑多的话
比如说单词可以跨行,又或者你要寻找的文件比较大
确定的字符串又贼长。。。
可以再考虑下性能问题
用kmp或类似的东西来搞
ps:
indexof我记得上直接找的