I am trying to write a function that takes three c-style strings, and returns a c-style string. This function searches a c-string for all occurrences of the sub-string and replaces them with a different string.
This program works but seems very inelegant. I can't help the feeling like it could have been done in a less bulky way.
char* replaceSubstring(char *original, char *from, char *to)
{
int origlen = strlen(original);
int i = 0;
int count = 0;
char *ptr;
//figure out how many times the sub-string occurs in a string.
//i couldn't figure out a way to avoid this loop
while (i<origlen)
{
ptr = strstr(original+i, from);
if (!ptr)
break;
else
{
i = ptr - original + 1;
count++;
}
}
//figure out what the size of the output string has to be
int newsize = origlen + (strlen(to) - strlen(from)) * count;
char *newstring = new char[newsize];
newstring[0] = '\0';
i = 0;
while (i < origlen)
{
ptr = strstr(original+i, from);
if (!ptr)
{
strcat(newstring,original+i);
break;
}
else
{
//this looks extremely ugly and bulky...
strncat(newstring, original+i, ptr-(original+i));
strcat(newstring, to);
i = i + ptr - (original + i) + strlen(from);
}
}
strcat(newstring,"\0");
return newstring;
}
Would anyone have any suggestions on how to make this code clearer and/or more efficient ? Any comments are welcome. Please do not suggest to use class string instead. That is not an option. The function must work with c-strings