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

51,934 answers

573 users

How to remove a given word from a string in C

1 Answer

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

int stringToArray2d(char str[], char words[][20]) {
	int i = 0, j = 0, k = 0;

	while (str[i] != 0) {
		if (str[i] == ' ') {
			words[k][j] = '\0';
			k++;
			j = 0;
		}
		else {
			words[k][j] = str[i];
			j++;
		}
		i++;
	}
	words[k][j] = '\0';

	return k + 1;
}


void removeWord(char str[], char to_remove[]) {
	char words[12][20] = { {""} };

	int len = stringToArray2d(str, words);

	memset(str, 0, strlen(str));

	for (int i = 0; i < len; i++) {
		if (strcmp(words[i], to_remove) != 0) {
			strcat(strcat(str, words[i]), " ");
		}
	}
}

int main()
{
	char str[] = "C is a general purpose computer programming language";
	char to_remove[] = "purpose";

	removeWord(str, to_remove);
	
	puts(str);

	return 0;
}





/*
run:
   
C is a general computer programming language
   
*/

 



answered Nov 18, 2022 by avibootz
edited Nov 19, 2022 by avibootz

Related questions

1 answer 81 views
1 answer 112 views
1 answer 89 views
1 answer 116 views
2 answers 128 views
2 answers 105 views
1 answer 102 views
...