substituting one string for another

I have a Linux C program I'm writing that has one section where, within a large string, I need to substitute a smaller string for another, and those probably won't be the same size.

For instance, if I have a string:

"Nowisthetimeforallgoodmen"

and I want to substitute 'most' for 'all' the main string will increase in size:

"Nowisthetimeformostgoodmen"

or a substitution that will increase the size of the main string:

"Nowisthetimefornogoodmen"

I thought I might get some opinions about what might be the best approach on something like this, besides some more cumbersome way of doing it. I've been looking at the C string functions to see if there's one that might be helpful, but I don't really see any.

Any help would be appreciated.

Look into the strstr() and strspn() functions.

There are actually many ways in which you can do this.

The first problem is the size of your string (char array). You can either use a fixed length array with a bound which you expect won't be exceeded (512 bytes for example) or you can work with dynamic length memory (malloc()/calloc()). I would advise you to use malloc() only as a last resort because it's slower/harder to maintain/prone to human error.

The second problem is choosing the appropriate way of doing the substitution. If you're replacing characters of the same size you could just do it directly like

char * p;
if ((p = strstr (array, "isthetime")) != NULL)
    strncpy (p, "new chars", strlen ("new chars")); 

and it should cause no problem. On the other hand if you're replacing characters with different lengths say "AAA" for "AAAA" you must have in mind that the substitution will overwrite one element in the array. If you wish to keep that element you must copy the array into a temporary array and then strncpy() it back to the original array after the replacing takes place.

You're third problem is having much caution with the terminating byte '\0' in your array. If you're not careful enough you might overwrite it and forget to replace it which in turn could lead to unexpected conditions.

PS: you can also use regcomp() and regexec() for pattern matching/replacing.