题目:
已知一个字符串,比如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;
}