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

51,892 answers

573 users

How to remove all occurrences of a word from a string in C

3 Answers

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

void RemoveAllOccurrencesOfWordFromString(char s[], char word[]) {
    int wordlen = strlen(word);
    int slen = strlen(s);
    char *p = s;
    
    while ( (p = strstr(p, word)) ) {
        int word_index = p - s; 
        for (int j = word_index, i = word_index + wordlen + 1; i < slen; i++, j++) {
            s[j] = s[i];
        }
        s[slen - wordlen] = '\0';
        p++;
    }
    
    s[slen - wordlen] = '\0';  
}
  
int main() {
    char s[50] = "c++ c python c++ java c++ php c++";
    char word[10] = "c++";
    
    RemoveAllOccurrencesOfWordFromString(s, word);
    
    puts(s);
}
  
 
   
/*
run:
   
c python java php 
 
*/

 



answered Apr 3, 2019 by avibootz
edited Oct 13, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ROWS 9
#define COLS 16

void RemoveAllOccurrencesOfWordFromString(char s[], char word[]) {
    char arr[ROWS][COLS];
    char *token = strtok(s, " ");
    int i = 0;
    
    while (token != NULL) {
        strcpy(arr[i++], token);
        token = strtok(NULL, " ");
    }
  
    s[0] = '\0';
    for (int i = 0; i < ROWS; i++) {
        if (strcmp (arr[i], word)) {
            strcat(strcat(s, arr[i]), " ");
        }
         
    }
    
    s[strlen(s) - 1] = '\0';        
}
  
int main() {
    char s[50] = "c++ c python c++ java c++ php c++";
    char word[10] = "c++";
    
    RemoveAllOccurrencesOfWordFromString(s, word);
    
    puts(s);
}

 
   
/*
run:
   
c python java php 
 
*/

 



answered Jan 19, 2021 by avibootz
edited Oct 13, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

void RemoveAllOccurrencesOfWordFromString(char *str, char *word) {
    char *pos, temp[512];
    int len = strlen(word);

    while ((pos = strstr(str, word)) != NULL) {
        strcpy(temp, pos + len);
        *pos = '\0';
         strcat(str, temp);
    }
}
  
int main() {
    char str[50] = "c++ c python c++ java c++ php c++";
    char word[10] = "c++";
    
    RemoveAllOccurrencesOfWordFromString(str, word);
    
    puts(str);
}


   
/*
run:
   
 c python  java  php 
 
*/

 



answered Oct 13, 2024 by avibootz

Related questions

1 answer 162 views
1 answer 128 views
2 answers 104 views
2 answers 111 views
1 answer 104 views
2 answers 132 views
...