#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char* replace_random_word(const char* s, const char* replacement_words[], int size) {
// Copy input string because strtok modifies it
char* temp = strdup(s);
if (!temp) return NULL;
// Split into words
char* words[128];
int count = 0;
char* token = strtok(temp, " ");
while (token && count < 128) {
words[count++] = token;
token = strtok(NULL, " ");
}
if (count == 0 || size == 0) {
free(temp);
return strdup(s);
}
// Pick random word index
int idx = rand() % count;
// Pick random replacement
const char* new_word = replacement_words[rand() % size];
// Build output string
char* result = malloc(strlen(s) + 32); // extra space for replacement
if (!result) {
free(temp);
return NULL;
}
result[0] = '\0';
for (int i = 0; i < count; i++) {
if (i == idx)
strcat(result, new_word);
else
strcat(result, words[i]);
if (i < count - 1)
strcat(result, " ");
}
free(temp);
return result;
}
int main() {
srand((unsigned)time(NULL));
const char* text = "The quick brown fox jumps over the lazy dog";
const char* replacement_words[] = {"c#", "c++", "java", "rust", "python"};
int size = sizeof(replacement_words) / sizeof(replacement_words[0]);
char* result = replace_random_word(text, replacement_words, size);
printf("%s\n", result);
free(result);
return 0;
}
/*
run:
The quick brown fox jumps c# the lazy dog
*/