个人认为直接利用String中IndexOf(String substr,int FromIndex)方法来实现可能会比较简单。代码如下:
- import java.lang.*;
- public class StringCounterDemo {
-
- static int SubStringCount(String str,String substr)
- {
- int count = 0,fromindex=0,k=0;
- int sub_len = substr.length();
- while(fromindex < str.length()){
- k=str.indexOf(substr, fromindex);
- if(k==-1)
- {
- break;
- }
- else
- {
- count ++;
- fromindex = k + sub_len;
- }
- }
- return count;
- }
- public static void main(String[] args) {
- // TODO 自动生成的方法存根
- System.out.println("SubCount = " +SubStringCount("abc","abcdef") );
- System.out.println("SubCount = " +SubStringCount("abcde","gf") );
- System.out.println("SubCount = " +SubStringCount("abcdeabab","ab") );
- }
- }
复制代码
|