#include <stdio.h>
#include <string.h>
int count (const char *str, const char *search);
int count (const char *str, const char *search)
{
int counter = 0,flag = 0;
const char *holdstr, *holdsearch;
do
{
for (holdstr = str, holdsearch = search ;
*holdsearch != '\0' && *holdstr == *holdsearch ;
holdsearch++,holdstr++) {}
if ( *holdsearch == '\0' )
{
counter++;
flag = 1;
}
}while (*(str++));
if (flag) return counter;
return -1;
}
int main()
{
const char *find = "the";
const char *arr1 = "the cat sat on the mat";
const char *arr2 = "theqqqqq cat sat on the mat";
const char *arr3 = "-qthe-- cat sat on theok mat";
int val = count(arr1, find);
printf("%d\n", val);
val = count(arr2, find);
printf("%d\n", val);
val = count(arr3, find);
printf("%d\n", val);
return 0;
}
我试图找到一对一的对应词。但是,我还得到了一些包含指定单词的其他单词。该函数类似于strstr()
。我也意识到它适用于strstr()
如何修复问题?
Output Expected Output
------- ---------------
2 2
2 1
2 0
答案 0 :(得分:1)
修复想法的样本
int count (const char *str, const char *search)
{
int counter = 0;
const char *holdstr, *holdsearch, *wordtop, *s=str;
do
{
for (wordtop = holdstr = s, holdsearch = search ;
*holdsearch != '\0' && *holdstr == *holdsearch ;
holdsearch++,holdstr++)
;
// top space end space
if (!*holdsearch && (wordtop == str || isspace(wordtop[-1])) && (!*holdstr || isspace(*holdstr)))
{
counter++;
}
}while (*s++);
return counter;//no needs flag if return 0;
}