题目:查找子字符串

题目:

已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,如果没有返回0,有的话返回子字符串的个数

自己调试的小程序,效率不高,就当练手吧:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/************************************************************************
*NAME:   int Find_Child_Chars(char *str_src, char *str_check)
*INPUT:  char *str_src         被查找的字符串
                char *str_check       要查找的字符
*OUTPUT: NULL
*RETURN: int                   返回查找到的字符串的个数,未找到则返回0
*STATE:  函数实现在源字符串里查找指定子字符串,若找到返回子字符串个数,
         若未找到返回0
 ***********************************************************************/
int Find_Child_Chars(char *str_src, char *str_check )
{
    int result = 0;
    int len_src = 0, len_check = 0, len_ck = 0, len_s = 0;
    int a = 0, b =0, c = 0, i = 0, j = 0, n = 0, k = 0;
    char tmp[100] = {'\0'};
    char ck[100] = {'\0'};
    char sr[100] = {'\0'};
    char *src = str_src;
    char *check = str_check;

    len_src = strlen(src);
    len_check = strlen(check);
    for(n = 0; n < len_check-1; n++)
    {
        ck[k++] = check[n];
    }
    for(a = 0; a < len_src-1; a++)
    {
        sr[b++] = src[a];
    }

    len_ck = strlen(ck);
    len_s = strlen(sr);
    for(i = 0; i < len_s; i++)
    {
        if(sr[i+len_ck-1] != ' ')
        {
            c = i;
            while(j < len_ck)
            {
                tmp[j++] = sr[c++];
            }
            if(!strcmp(tmp, ck))
            {
                result++;
            }
        }
        else
        {
             continue;
        }
        memset(tmp, 0, 100);
        j = 0;
    }

    return result;
}

/************************************************************************
*STATE: 输入源字符串和要查找的子字符串,在源字符串里查找指定子字符串,
               若找到返回子字符串个数,若未找到返回0
 ***********************************************************************/
int main(viod)
{
    int result = 0;
    int size =1024;
    char buff1[1024] = {'\0'};
    char buff2[1024] = {'\0'};

    printf("Please input the source string:\n");
    fgets(buff1, size, stdin);
    printf("-----------------------------------------\n");
    printf("Please input the check strings:\n");
    fgets(buff2, size, stdin);
    printf("-----------------------------------------\n");

    result = Find_Child_Chars(buff1, buff2);
    printf("the result is : %d\n", result);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值