String s = null;
String s1 = "1\n1 2\n1 2 3\n1 2 3 4\n";
// System.out.println(s1);
StringBuffer sb = new StringBuffer();
int linenum = 0;
int count = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("c:/t.txt"))); while (((s = br.readLine())) != null) { if (s.trim().length() != 0) {
linenum++;
sb.append(s.trim());
sb.append("\n");
} else if (sb.toString().equals(s1)) {
count++; sb.delete(0, sb.length()); } else {
linenum = 0;
sb.delete(0, sb.length());
}
} if (sb.toString().equals(s1))
count++;
System.out.println("find" + count + "'s");代码如上,本想在文件中读出相应的矩阵,然后删除,但是不知道该怎么定位这个矩阵然后删除,请指点,最好又核心代码,谢谢!
String s1 = "1\n1 2\n1 2 3\n1 2 3 4\n";
// System.out.println(s1);
StringBuffer sb = new StringBuffer();
int linenum = 0;
int count = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("c:/t.txt"))); while (((s = br.readLine())) != null) { if (s.trim().length() != 0) {
linenum++;
sb.append(s.trim());
sb.append("\n");
} else if (sb.toString().equals(s1)) {
count++; sb.delete(0, sb.length()); } else {
linenum = 0;
sb.delete(0, sb.length());
}
} if (sb.toString().equals(s1))
count++;
System.out.println("find" + count + "'s");代码如上,本想在文件中读出相应的矩阵,然后删除,但是不知道该怎么定位这个矩阵然后删除,请指点,最好又核心代码,谢谢!
假如内容没读完,则第一个条件( ( s = br.readLine() ) != null )一直为真:从这个意思上说,你的else if (sb.toString().equals(s1)) 及else都没多大意义。简单点,你可以像以下这样写: public static void main(String[] args) throws Exception {
String s = null;
String s1 = "1\n1 2\n1 2 3\n1 2 3 4\n";
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("c:/t.txt"));
int count = 0;
int start;
while ( ( s = br.readLine() ) != null ) {
sb.append( s.trim() + "\n" );
if( ( start = sb.indexOf( s1 ) ) >= 0 )
{
sb.delete(start, start + s1.length() );
count ++;
}
} System.out.println("find" + count + "'s");
//如果必要,可以把sb的内容写入文件
System.out.println( sb );
}
sb.delete(start, start + s1.length() );
这句中,start就是开始的标记,而start+s1.length()就相当于结束的标记。从这个意义上来说,其实我们的思路是一样的。呵呵。
发现代码又点问题,刚才忽略了,
if( ( start = sb.indexOf( s1 ) ) >= 0 )
{
sb.delete(start, start + s1.length() );
count ++;
}
这里如果一个矩阵包涵s1但是比s1大,那么这个矩阵也算作s1了,就不符合标准了,还是要通过空行来判断一个矩阵是否读完。 还是感觉你的思路。
String s1 = "1\n1 2\n1 2 3\n1 2 3 4\n\n";