比如String a = "afafdfaffd";String b = "af";如何求b在a中出现的次数

解决方案 »

  1.   

    public class Test {
    public static void main(String[] args) {
    String  a = "afafdfaffd";
    String  b = "af";
    int sum=0;
    while(a.indexOf(b)!=-1){
    sum++;
    a=a.substring(b.length()+1);
    }
    System.out.println("b在a中出现的次数为:"+sum);
    }
    }
      

  2.   

    String a = "afafdfaffd";
    String b = "af";
    System.out.println(a.split(b,-1).length -1);這是最簡單的方法。
    (考慮字串有可能在尾端,所以用 split(b,-1)。)
      

  3.   

    import java.io.*;public class file_1 {    public static void main(String[] args) {
            String a = "ronsronsrons";
            String b = "ron";
            int num = 0;
            boolean flag = true;
            while (flag) {
                int from = a.indexOf(b);
                if (from >= 0) {
                    a = a.substring(from + b.length());
                    num++;
                } else
                    flag = false;        }
            System.out.println(num);
        }

      

  4.   

    用String 自带的substring方法和index方法就可以实现了,不过我为了练手自己用正则再弄了一下,呵呵。就算是作业题,楼主也最好自己把代码抄一遍到记事本上自己跑一次吧
    package csdn.javase.regular.regex1;
    import java.util.regex.*;
    /**
     * number of the substrings
     * @author supercodingman
     * @version 1.0
     */
    public class RegularEx2 {

    public int numSubString(String regs,String initString){
    int i = 0;
    Matcher m = Pattern.compile(regs).matcher(initString);
    while(m.find()){
    System.out.println(m.group()+":"+m.start());
    i++;
    }
    if(i == 0){
    System.out.println("No such substring exists!");
    }
    return i;
    }

    public static void main(String [] args){
    String reg = "af";
    String exp = "afafdfaffd";
    RegularEx2 ex2 = new RegularEx2();
    int j = ex2.numSubString(reg, exp);
    System.out.println("The number of the substring "+reg+" is:"+j);
    }
    }
      

  5.   

    class Test32 {

    public int getCount(String longstr,String shortstr) {
    int count=0;
    int longlength = longstr.length();
    int shortlength = shortstr.length();
    for(int i=0; i<longlength-1; i++) {
    String tmpstr = longstr.substring(i,shortlength+i);
    if(tmpstr.equals(shortstr))
    count++;
    }

    return count;
    }

    public static void main(String[] args) {
    Test32 t32 = new Test32();
    System.out.print(t32.getCount("aacbcssafbc", "ab"));
    }
    }//结帖
      

  6.   

    public static void main(String[] args) {   
            Matcher m = Pattern.compile("af").matcher("afafdfaffd");
            int i = 0;
            while (m.find())
             i++;
            System.out.print(i);
        }