fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5.  
  6. #define TEXT_SIZE 1000000
  7. #define KEY "mouri"
  8. #define KEY_SIZE (sizeof(KEY) - 1)
  9.  
  10. // 乱数によるアルファベット文字列生成
  11. void generate_random_text(char *text, int size) {
  12. const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
  13. for (int i = 0; i < size; i++) {
  14. text[i] = alphabet[rand() % (sizeof(alphabet) - 1)];
  15. }
  16. text[size] = '\0';
  17. }
  18.  
  19. // 文字列を探索する関数
  20. char* search(char *text, const char *key) {
  21. int m = strlen(text);
  22. int n = strlen(key);
  23. for (char *p = text; p <= text + m - n; p++) {
  24. if (strncmp(p, key, n) == 0) {
  25. return p;
  26. }
  27. }
  28. return NULL;
  29. }
  30.  
  31. int main() {
  32. // 乱数のシードを設定
  33. srand(time(NULL));
  34.  
  35. // 乱数による1000000文字のアルファベット文字列を生成
  36. char text[TEXT_SIZE + 1];
  37. generate_random_text(text, TEXT_SIZE);
  38.  
  39. // キーを探索
  40. char *p = search(text, KEY);
  41. while (p != NULL) {
  42. printf("keyは%d文字目から%d文字目までで、それ以降の文字列は表示しません\n",
  43. p - text + 1, p - text + 1 + KEY_SIZE);
  44. p = search(p + KEY_SIZE, KEY);
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0.02s 5284KB
stdin
Standard input is empty
stdout
Standard output is empty