问题描述:
这个函数的问题是它会处理所有的子字符串,而不是像这样的词,例如,如果我在“hifive toeveryone”中寻找“hi”,它会返回 1
- int HowManyString(char *satz,char *word) {
- int coun = 0;
- while (strlen(word)<strlen(satz)) {
- if (strstr(satz,word)==NULL) {
- return coun;
- } else {
- satz=strstr(satz,word)+strlen(word);
- if(*(satz)==' '||*(satz)=='\0'){
- coun++;
- } else {
- return coun;
- }
- }
- }
- return coun;
- }
解决思路一:
这是一个实现您正在寻找的功能:
- int count_words(const char *sentence, const char *word)
- {
- int counter = 0;
-
- for (const char *p = sentence; *p; ++p) {
- // Skip whitespaces
- if (isspace(*p))
- continue;
-
- // Attempt to find a match
- const char *wp = word, *sp = p;
- while (*wp != '\0' && *sp != '\0' && *wp == *sp) {
- ++wp;
- ++sp;
- }
-
- // Match found AND a space after AND a space before
- if (*wp == '\0' && (isspace(*sp) || *sp == '\0') && (p == sentence || isspace(*(p-1)))) {
- ++counter;
- p = sp - 1;
- }
-
- // End of sentence reached: no need to continue.
- if (*sp == '\0')
- return counter;
- }
-
- return counter;
- }
用法:
- int main(void)
- {
- const char sentence[] = "I is Craig whoz not me, not him, not you!";
- const char word[] = "not";
-
- int occ = count_words(sentence, word);
-
- printf("There are %d occurences.\n", occ);
- }
输出:
There are 3 occurences.
解决思路二(这是解决小编问题的思路):
以上仅为部分解决思路介绍,请查看全部内容,请添加下方公众号后回复001,即可查看。公众号有许多评分最高的编程书籍和其它实用工具,绝对好用,可以放心使用
如果您觉得有帮助,可以关注公众号——定期发布有用的资讯和资源