C implementation - count the number of times the substring appears in the parent string (specifically)

Code

        Idea: Each loop takes the substring characters and compares them with the parent string characters, and then moves backwards to record how many consecutive characters in the parent string are the same as the substring characters. (The program has been annotated in detail and will not be repeated here)

//导入头文件
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
    int i,j,k;//控制循环
	int count=0;//计数器 
    char T[50];//定义母串,容量50
	char P[10];//定义子串,容量10
    printf("请输入 母串:\n");//信息提示 
    gets(T);//读取数据 
    printf("请输入 子串:\n");//信息提示
    gets(P);//读取数据 
    int TLen=strlen(T);//母串长度 
    int 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);
    return 0;
}

operation result

 

Guess you like

Origin blog.csdn.net/m0_54158068/article/details/124372127