fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5.  
  6. // 文字列ランダム生成の関数
  7. void generate_random_string(char *str, int length) {
  8. const char charset[] = "abcdefghijklmnopqrstuvwxyz";
  9. for (int i = 0; i < length; i++) {
  10. int key = rand() % (int)(sizeof(charset) - 1);
  11. str[i] = charset[key];
  12. }
  13. str[length] = '\0';
  14. }
  15.  
  16. // 探索関数
  17. char* search(char *text, const char *key) {
  18. int m, n;
  19. char *p;
  20. m = strlen(text);
  21. n = strlen(key);
  22. for (p = text; p <= text + m - n; p++) {
  23. if (strncmp(p, key, n) == 0)
  24. return p;
  25. }
  26. return NULL;
  27. }
  28.  
  29. int main() {
  30. srand(time(NULL)); // 乱数の種を初期化
  31. int length = 1000000;
  32. char *text = (char *)malloc(length + 1); // 100万文字用のメモリを確保
  33. char *key = "mouri";
  34. char *p;
  35. int count = 0;
  36.  
  37. generate_random_string(text, length);
  38.  
  39. p = search(text, key);
  40. while (p != NULL) {
  41. count++;
  42. printf("keyは%d桁目から%d桁目までで、それ以下の文字列は%sとなります\n",
  43. p - text + 1, p - text + 1 + strlen(key), p);
  44. p = search(p + 1, key); // オーバーラップを避けないようにポインタを1つ進める
  45. }
  46.  
  47. printf("文字列 '%s' は生成された文字列に %d 回出現しました。\n", key, count);
  48.  
  49. free(text); // 確保したメモリを解放
  50. return 0;
  51. }
Success #stdin #stdout 0.03s 5280KB
stdin
Standard input is empty
stdout
文字列 'mouri' は生成された文字列に 0 回出現しました。