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 the last n occurrences of a substring in a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
void remove_last_n(char *s, const char *sub, int n) {
    int len = strlen(s);
    int sublen = strlen(sub);
    int positions[128];
    int count = 0;
 
    // Find all occurrences
    for (int i = 0; i <= len - sublen; i++) {
        if (strncmp(&s[i], sub, sublen) == 0) {
            positions[count++] = i;
        }
    }
 
    // Remove last n occurrences
    for (int i = count - 1; i >= 0 && n > 0; i--, n--) {
        int pos = positions[i];
        memmove(&s[pos], &s[pos + sublen], strlen(&s[pos + sublen]) + 1);
    }
}
 
void remove_extra_spaces(char *s) {
    int i = 0, j = 0;
    int space = 0;
 
    // Skip leading spaces
    while (isspace((unsigned char)s[i])) i++;
 
    for (; s[i] != '\0'; i++) {
        if (isspace((unsigned char)s[i])) {
            if (!space) {
                s[j++] = ' ';
                space = 1;
            }
        } else {
            s[j++] = s[i];
            space = 0;
        }
    }
 
    // Remove trailing space
    if (j > 0 && s[j - 1] == ' ')
        j--;
 
    s[j] = '\0';
}
 
int main() {
    char text[256] = "abc xyz xyz abc xyzabcxyz abc";
 
    remove_last_n(text, "xyz", 3);
    printf("%s\n", text);
    
    remove_extra_spaces(text);
    printf("%s\n", text);
 
    return 0;
}

 
 
/*
run:
 
abc xyz  abc abc abc
abc xyz abc abc abc
 
*/

 



answered 6 hours ago by avibootz
edited 2 hours ago by avibootz
...