#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
*/