#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// 文字列ランダム生成の関数
void generate_random_string(char *str, int length) {
const char charset[] = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < length; i++) {
int key
= rand() % (int)(sizeof(charset
) - 1); str[i] = charset[key];
}
str[length] = '\0';
}
// 探索関数
char* search(char *text, const char *key) {
int m, n;
char *p;
for (p = text; p <= text + m - n; p++) {
return p;
}
return NULL;
}
int main() {
int length = 1000000;
char *text
= (char *)malloc(length
+ 1); // 100万文字用のメモリを確保 char *key = "mouri";
char *p;
int count = 0;
generate_random_string(text, length);
p = search(text, key);
while (p != NULL) {
count++;
printf("keyは%d桁目から%d桁目までで、それ以下の文字列は%sとなります\n", p
- text
+ 1, p
- text
+ 1 + strlen(key
), p
); p = search(p + 1, key); // オーバーラップを避けないようにポインタを1つ進める
}
printf("文字列 '%s' は生成された文字列に %d 回出現しました。\n", key
, count
);
free(text
); // 確保したメモリを解放 return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHN0cmluZy5oPgojaW5jbHVkZSA8dGltZS5oPgoKLy8g5paH5a2X5YiX44Op44Oz44OA44Og55Sf5oiQ44Gu6Zai5pWwCnZvaWQgZ2VuZXJhdGVfcmFuZG9tX3N0cmluZyhjaGFyICpzdHIsIGludCBsZW5ndGgpIHsKICAgIGNvbnN0IGNoYXIgY2hhcnNldFtdID0gImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6IjsKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbGVuZ3RoOyBpKyspIHsKICAgICAgICBpbnQga2V5ID0gcmFuZCgpICUgKGludCkoc2l6ZW9mKGNoYXJzZXQpIC0gMSk7CiAgICAgICAgc3RyW2ldID0gY2hhcnNldFtrZXldOwogICAgfQogICAgc3RyW2xlbmd0aF0gPSAnXDAnOwp9CgovLyDmjqLntKLplqLmlbAKY2hhciogc2VhcmNoKGNoYXIgKnRleHQsIGNvbnN0IGNoYXIgKmtleSkgewogICAgaW50IG0sIG47CiAgICBjaGFyICpwOwogICAgbSA9IHN0cmxlbih0ZXh0KTsKICAgIG4gPSBzdHJsZW4oa2V5KTsKICAgIGZvciAocCA9IHRleHQ7IHAgPD0gdGV4dCArIG0gLSBuOyBwKyspIHsKICAgICAgICBpZiAoc3RybmNtcChwLCBrZXksIG4pID09IDApCiAgICAgICAgICAgIHJldHVybiBwOwogICAgfQogICAgcmV0dXJuIE5VTEw7Cn0KCmludCBtYWluKCkgewogICAgc3JhbmQodGltZShOVUxMKSk7IC8vIOS5seaVsOOBrueoruOCkuWIneacn+WMlgogICAgaW50IGxlbmd0aCA9IDEwMDAwMDA7CiAgICBjaGFyICp0ZXh0ID0gKGNoYXIgKiltYWxsb2MobGVuZ3RoICsgMSk7IC8vIDEwMOS4h+aWh+Wtl+eUqOOBruODoeODouODquOCkueiuuS/nQogICAgY2hhciAqa2V5ID0gIm1vdXJpIjsKICAgIGNoYXIgKnA7CiAgICBpbnQgY291bnQgPSAwOwoKICAgIGdlbmVyYXRlX3JhbmRvbV9zdHJpbmcodGV4dCwgbGVuZ3RoKTsKCiAgICBwID0gc2VhcmNoKHRleHQsIGtleSk7CiAgICB3aGlsZSAocCAhPSBOVUxMKSB7CiAgICAgICAgY291bnQrKzsKICAgICAgICBwcmludGYoImtleeOBryVk5qGB55uu44GL44KJJWTmoYHnm67jgb7jgafjgafjgIHjgZ3jgozku6XkuIvjga7mloflrZfliJfjga8lc+OBqOOBquOCiuOBvuOBmVxuIiwKICAgICAgICAgICAgICAgcCAtIHRleHQgKyAxLCBwIC0gdGV4dCArIDEgKyBzdHJsZW4oa2V5KSwgcCk7CiAgICAgICAgcCA9IHNlYXJjaChwICsgMSwga2V5KTsgLy8g44Kq44O844OQ44O844Op44OD44OX44KS6YG/44GR44Gq44GE44KI44GG44Gr44Od44Kk44Oz44K/44KSMeOBpOmAsuOCgeOCiwogICAgfQoKICAgIHByaW50Zigi5paH5a2X5YiXICclcycg44Gv55Sf5oiQ44GV44KM44Gf5paH5a2X5YiX44GrICVkIOWbnuWHuuePvuOBl+OBvuOBl+OBn+OAglxuIiwga2V5LCBjb3VudCk7CgogICAgZnJlZSh0ZXh0KTsgLy8g56K65L+d44GX44Gf44Oh44Oi44Oq44KS6Kej5pS+CiAgICByZXR1cm4gMDsKfQ==