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,907 questions

51,839 answers

573 users

How to remove a random word from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void remove_random_word(char *str) {
    char *words[128];
    int word_count = 0;
    char *token = strtok(str, " ");
   
    // Split the string into words
    while (token != NULL) {
        words[word_count++] = token;
        token = strtok(NULL, " ");
    }
    
    // Seed the random number generator
    srand(time(NULL));

    // Select a random word to remove
    int random_index = rand() % word_count;

    // Reconstruct the string without the random word
    char tmpStr[1024] = "";
    for (int i = 0; i < word_count; i++) {
        if (i != random_index) {
            strcat(strcat(tmpStr, words[i]), " ");
        }
    }
    
    tmpStr[strlen(tmpStr) - 1] = '\0';
    
    
    strcpy(str, tmpStr);
}

int main() {
    char str[] = "Im not clumsy The floor just hates me";
    printf("str: %s\n", str);
    
    remove_random_word(str);
    printf("result: %s\n", str);
    
    return 0;
}


/*
run:

str: Im not clumsy The floor just hates me
result: Im not clumsy floor just hates me

*/

 



answered May 4, 2025 by avibootz

Related questions

4 answers 354 views
1 answer 127 views
1 answer 64 views
1 answer 92 views
1 answer 170 views
1 answer 73 views
...