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

51,888 answers

573 users

How to remove the last occurrence of a word from a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
    
int main() {
    char s[50] = "c++ c python c++ java c++ php";
    char *p = s, *last_p;
    char word[10] = "c++";
    
    while( (p = strstr(p, word)) ) {
        last_p = p;
        p++;
    }
   
    int word_index = last_p - s; 
     
    for (int j = word_index, i = word_index + strlen(word) + 1; i < strlen(s); i++, j++) {
        s[j] = s[i];
    }
         
    s[strlen(s) - strlen(word)] = '\0';
                     
    puts(s);
    
}
    
    
     
/*
run:
     
c++ c python c++ java php 
    
*/

 



answered Sep 8, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

void remove_last_occurrence(char *s, const char *word) {
    char *p = s;
    char *last_p = NULL;

    // Find last occurrence
    while ((p = strstr(p, word)) != NULL) {
        last_p = p;
        p++;  // move forward to find next
    }

    if (last_p == NULL)
        return; // word not found

    int word_len = strlen(word) + 1;
    int start = last_p - s;  // index of last occurrence

    // Shift characters left to remove the word
    for (int j = start, i = start + word_len; s[i] != '\0'; i++, j++) {
        s[j] = s[i];
    }

    // Null-terminate the shortened string
    s[strlen(s) - word_len] = '\0';
}

int main() {
    char s[50] = "c++ c python c++ java c++ php";

    remove_last_occurrence(s, "c++");

    puts(s);
}



/*
run:

c++ c python c++ java php

*/

 



answered 3 hours ago by avibootz
...