C 練習實例96
題目:計算字串中子串出現的次數 。
程式分析:無。
實例
// Created by www.xuhuhu.com on 15/11/9.
//
//
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i,j,k,TLen,PLen,count=0;
char T[50],P[10];
printf("請輸入兩個字串,以回車隔開,母串在前,子串在後:\n");
gets(T);
gets(P);
TLen=strlen(T);
PLen=strlen(P);
for(i=0;i<=TLen-PLen;i++)
{
for(j=0,k=i;j<PLen&&P[j]==T[k];j++,k++)
;
if(j==PLen)count++;
}
printf("%d\n",count);
system("pause");
return 0;
}
以上實例運行輸出結果為:
請輸入兩個字串,以回車隔開,母串在前,子串在後: abca a 2