以下程序的目的是找一个文件中ab字符的个数,一行可能有多个ab应如何实现呢
import java.io.*;public class seartxt4
{ public static void main(String[] args) throws Exception {
 FileReader in =new FileReader("abc.txt");
 BufferedReader br=new BufferedReader(in);
 String c;
 int b=0; String searytxt="ab";
    while ((c=br.readLine())!=null){
int e=0;
// for(int i=1;i<c.length();i++){
    e=c.indexOf(searytxt,e);
if (e>0)
{
b=b+1;
//e=e+seartytxt.length();
System.out.println(b);
}
//System.out.println (e);

// }

//System.out.println(String.valueOf(c));
//System.out.println(c);
    // if  (searytxt.compareTo(String.valueOf(c))==0){
    // b=b++;
    // }    }
    System.out.print(b);
    in.close() ; }};

解决方案 »

  1.   

    public static int repeatStr(String ostr,String gstr){
    int total = 0;
    int index = ostr.indexOf(gstr);
    while(index!=-1){
    total++;
    System.out.println(index);
    index = ostr.indexOf(gstr,index+gstr.length());
    }

    return total;
    }
      

  2.   

    以下程序只可以查到每一行的第一个配对的,找不到后面.
    import java.io.*;public class seartxt4
    { public static void main(String[] args) throws Exception {
     FileReader in =new FileReader("abc.txt");
     BufferedReader br=new BufferedReader(in);
     String c;
     int b=0; String searytxt="abc";
        while ((c=br.readLine())!=null){
    int e=0;
    //for(int i=1;i<c.length();i++){
        e=c.indexOf(searytxt,e);
    if (e>0)
    {
    b=b+1;

    //e=e+3;
    //System.out.println(b);
    }
    //System.out.println (e);

    // }

    //System.out.println(String.valueOf(c));
    //System.out.println(c);
        // if  (searytxt.compareTo(String.valueOf(c))==0){
        // b=b++;
        // }    }
        System.out.print(b);
        in.close() ; }};
      

  3.   

    /**
     * 获得字符串中某一字符串的个数
     * @param ostr 原字符串
     * @param gstr 检查的字符串
     * @return 个数
     */
    public static int repeatStr(String ostr,String gstr){
    int total = 0;
    int index = ostr.indexOf(gstr);
    while(index!=-1){
    total++;
    index = ostr.indexOf(gstr,index+gstr.length());
    }

    return total;
    }把这个方法加入到你的代码中计算每一行中的个数,然后每一行求总和就OK了