当前位置:网站首页>[pointer] counts the number of times one string appears in another string

[pointer] counts the number of times one string appears in another string

2022-07-06 14:36:00 |Light|

requirement

Make up a function , Count the number of times one string appears in another string .( Use a pointer to achieve )

Code

#include<stdio.h>
#include<string.h>
/* *  This function is used to count substrings substr In string str Is the number of times  *  The number of times after statistics is returned in the form of function value  */
int freq_substring(char* str,char* substr)
{
    
    int f=0;
    int i,j=0,k,l,l1;
    l = strlen(str);
    l1 = strlen(substr);
    for(i=0;i<l;i++)
    {
    
        if(str[i]!=substr[0])
        continue;
        else
        {
    
            for(j=0;j<l1;j++)
            {
    
                if(str[i+j] == substr[j])
                {
    
                    if(j+1 == l1)
                    f++;
                    else
                    continue;
                }
                else
                break;
            }
        }
    }
    return f;
}

main function

int main()
{
      
    char str[300],substr[50];
    int n;
    gets(str);
    gets(substr);
    n=freq_substring(str,substr);
    printf("%d\n",n);
 }   

test

Test input
Good luck, good health, good cheer. I wish you a happy New Year.
ood
Output
3

原网站

版权声明
本文为[|Light|]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918541695.html