Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,919 questions

51,852 answers

573 users

How to replace a random word in a string with a random word from an array of words using C

1 Answer

0 votes
#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
  
*/

 



answered 4 hours ago by avibootz

Related questions

2 answers 152 views
...