The concept of string in C is a low-level one: an array of characters. Just as you cannot take an array of integers and directly replace one of its integers with a whole other array, you cannot directly replace a character of a string with another string. You must first allocate the necessary memory for the extra characters that you want to jam into your original string.
Below I offer a code that will do that. It isn't the most efficient, but gives you an idea of how this should work. It is inefficient because it first goes through the whole string counting the special symbols that are going to be replaced and figuring out how much extra space is needed, then it goes over it again when it copies the characters.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *replace(const char *s)
{
size_t i, j;
size_t len, extra;
char *r = NULL;
len = strlen(s);
extra = 0;
/* First we count how much extra space we need */
for (i = 0; i < len; ++i) {
if (s[i] == '&')
extra += strlen("&") - 1;
else if (s[i] == '<')
extra += strlen("<") - 1;
else if (s[i] == '>')
extra += strlen(">") - 1;
}
/* Allocate a new string with the extra space */
r = malloc(len + extra + 1);
assert(r != NULL);
/* Put in the extra characters */
j = 0;
for (i = 0; i < len; ++i) {
if (s[i] == '&') {
r[j++] = '&';
r[j++] = 'a';
r[j++] = 'm';
r[j++] = 'p';
r[j++] = ';';
} else if (s[i] == '<') {
r[j++] = '&';
r[j++] = 'l';
r[j++] = 't';
r[j++] = ';';
} else if (s[i] == '>') {
r[j++] = '&';
r[j++] = 'g';
r[j++] = 't';
r[j++] = ';';
} else {
r[j++] = s[i];
}
}
/* Mark the end of the new string */
r[j] = '\0';
/* Just to make sure nothing fishy happened */
assert(strlen(r) == len + extra);
return r;
}
int main(void)
{
const char *sorig = "this &, this >, and this < are special characters";
char *snew;
snew = replace(sorig);
printf("original : %s\n", sorig);
printf(" new : %s\n", snew);
free(snew);
return 0;
}
A better strategy would be to define a lookup table or map so that you can include or exclude new pairs of symbols and their replacements just by changing the table. You can also use strncpy
for this, avoiding the character by character treatment. The example above is just to illustrate what goes on under the hood.