Java中查找子串出现次数

方法一:采用String类中indexOf()方法;
public class SubStringCount {

  public static void main(String[] args) {

    String str1 = "abcjavanbajavasrcjavammmjava";
    String str2 = "java";

    int count = 0;
    int index=str1.indexOf(str2);

    while(index!=-1){
      index = str2.length() + index;
      count++;
      index = str1.indexOf(str2, index);
    }
    System.out.println(count);
  }

}

方法二:采用String类中substring()方法;


public class SubStringCount {

  public static void main(String[] args) {

    String str1 = "abcjavanbajavasrcjavammmjava";
    String str2 = "java";

    int count = 0;
    int index = 0;

    while((index=str1.indexOf(str2))!=-1){
      index = str2.length() + index;
      count++;
      str1 = str1.substring(index, str1.length());
    }
    System.out.println(count);
  }

}

posted @ 2018-12-18 17:37  文所未闻  阅读(719)  评论(0编辑  收藏  举报