-2

好吧,标题已经说明了我的需要。我尝试使用循环,但效果不佳,所以,我来寻求你们的帮助!

这是我的代码:

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


int main()
{
    char word[31], word2[31];
    int size1, size2;
    int i, j, k; // control
    int count = 0;

        printf ("\nInput the first word");
        scanf ("%s", word);
        printf ("\nInput the second word: ");
        scanf (" %s", word2);

// I tried  to make  a loop through the first string and if it matches a letter, it would loop through the others (if they are equal, we have a substring), but failed to put it on the `for` loop


printf ("'%s' appears %d times within '%s'", word2, count, word);

return 0;
}
4

2 回答 2

4

strstr是一个有用的功能,它大大缩短了你的代码;当您找到匹配项时,只需使用字符串的其余部分重试;

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

int main()
{
  const char* source = "aabaa";
  const char* string2find = "aa";

  int occurrences;
  const char *ptr, *lastfind = NULL;

  for(ptr=source; (lastfind=strstr(ptr, string2find)); ptr=lastfind+1)
    occurrences++;

  printf("%d\n", occurrences);

  return 0;
}

...或者如果您真的打算在没有 string.h 函数的情况下执行此操作,那么代码会变得更加冗长;

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

int main()
{
  const char* source = "aaabaa";
  const char* string2find = "aa";

  int count=0;
  const char *position;
  for(position=source; *position; position++) {
      int comparepos, equal=1;
      for(comparepos=0; string2find[comparepos]; comparepos++) {
         if(position[comparepos] != string2find[comparepos]) {
             equal = 0;
             break;
         }
      }
      count+=equal;
  }

  printf("%d\n", count);

  return 0;
}
于 2013-02-10T18:50:15.087 回答
1

用于strstr查找其他字符串中出现的字符串:

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

int main () {
    char* a = "aaaa";
    char* b = "aa";
    char* c;
    int count = 0;
    for(c = a; *c; c++){
        if(strstr(c, b)){
            count++;
        }
    }
    printf("count %d\n", count);
}

另外,用于strlen查找字符串的长度..

于 2013-02-10T18:43:35.027 回答