fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5.  
  6. void generate_random_string(char *str, int length) {
  7. const char charset[] = "abcdefghijklmnopqrstuvwxyz";
  8. for (int i = 0; i < length; i++) {
  9. int key = rand() % (int)(sizeof(charset) - 1);
  10. str[i] = charset[key];
  11. }
  12. str[length] = '\0';
  13. }
  14.  
  15. char* search(char *text, char *key) {
  16. int m, n;
  17. char *p;
  18. m = strlen(text);
  19. n = strlen(key);
  20. for (p = text; p <= text + m - n; p++) {
  21. if (strncmp(p, key, n) == 0)
  22. return p;
  23. }
  24. return NULL;
  25. }
  26.  
  27. int main(void) {
  28. srand(time(NULL)); // 乱数の種を初期化
  29. int length = 1000000;
  30. char *text = (char *)malloc(length + 1); // 100万文字用のメモリを確保
  31. char *key = "mouri";
  32. char *p;
  33. int count = 0;
  34.  
  35. // ランダムな文字列を生成
  36. generate_random_string(text, length);
  37.  
  38. // 文字列 "mouri" を探索し、カウント
  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.02s 5272KB
stdin
Standard input is empty
stdout
文字列 'mouri' は生成された文字列に 0 回出現しました。