-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 に答える