Based on suggestions in this question here, I've written the following program that finds, and replaces, a target substring in a string. (It could be run in a loop to find and replace all instances of "target" using the strstr()
string method, but I just give an example here.)
#include <stdio.h>
#include <string.h>
#define SUCCESS 1
#define FAILURE 0
#define STR_CAP 80 + 1
int stringify(char *string, const char *target, const char *replacement) {
char segment[STR_CAP];
int S = strlen(string), T = strlen(target);
char pre_segment[STR_CAP];
char post_segment[STR_CAP];
for (int i = 0; i < S; i++) {
strncpy(segment, string + i, T);
segment[T] = '\0';
if (strcmp(segment, target) == 0) {
memcpy(pre_segment, string, i);
/*printf("pre_segment: %s\n", pre_segment);*/
pre_segment[i] = '\0';
memcpy(post_segment, string + i + T, S - (i + T));
post_segment[S - (i + T)] = '\0'; /*WHAT IS THIS MAGIC?*/
/*printf("post_segment: %s\n", post_segment);*/
strcat(pre_segment, replacement);
/*printf("pre_segment after concat.: %s\n", pre_segment);*/
strcat(pre_segment, post_segment);
/*printf("pre_segment after concat,: %s\n", pre_segment);*/
strcpy(string, pre_segment);
return SUCCESS;
}
} return FAILURE;
}
int main() {
char string[] = "The quick brown fox jumped over the lazy, brown dog.";
char target[] = "brown";
char replacement[] = "ochre-ish";
stringify(string, target, replacement);
printf("%s\n", string);
stringify(string, target, replacement);
printf("%s\n", string);
return 0;
}
But there are some things I don't understand.
(1) For one thing: before I used memcpy()
and manually set the ends of the strings I copied to '\0'
, I kept getting buffer-overflows (in the form of stack-smashing), and weird errors. What effect does this have that just naively using strncpy()
doesn't? For example, if you comment out the "MAGIC" line, the program just about implodes.
(2) Is there a nicer or more canonical way of doing this? This feels very clunky, but I couldn't find any basic "how-tos" on substring replacement.