1. 程式人生 > >下面的函式統計子字串substr在字串str中出現的次數,如果substr在str中不出現,則返回值0

下面的函式統計子字串substr在字串str中出現的次數,如果substr在str中不出現,則返回值0

c++

#include<iostream>
#include<string>
using namespace std;

int str_count(string substr, string str)
{
    int times=0, num=0,i=0;
    int a=substr.length();
    int b=str.length();
    if(a>b)
      return 0;
    else
    {
        for(int i=0;i<b;i++)
        {   
            if(str[i]==substr[0
]) for(int j=0;j<a;j++) { if(str[i+j]==substr[j]) { num++; continue; } else break
; } } times=num/a; return times; } } int main() { string str; cout<<"plz input str:"<<endl; cin>>str; string substr; cout<<"plz input substr:"<<endl; cin>>substr; cout<<"the repeated is "
<<str_count(substr,str)<<" times"<<endl; while(1); return 0; }

java: 暴力方法

//substr在str中出現的次數
public class Substr {
    public static void main(String[] args) {
        String str = "ajavabjavacjavadjavaejavafjava";
        String substr = "java";
        int len = substr.length();
        int index ;
        int count = 0;

        while( (index=(str.indexOf(substr)) )!= -1) {
            count ++;
            str = str.substring(index+len);
        }
        System.out.println(count);      
    }

}