M
Mike Semko
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.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char* replaceSubstring(char*,char*,char*);
char *string1, *string2, *string3;
string1 = "the dog jumped over the fence";
string2 = "the";
string3 = "that";
cout << replaceSubstring(string1,string2,string3);
}
char* replaceSubstring(char *original, char *from, char *to)
{
int origlen = strlen(original);
int i = 0;
int count = 0;
char *ptr;
while (i<origlen)
{
ptr = strstr(original+i, from);
if (!ptr)
break;
else
{
i = ptr - original + 1;
count++;
}
}
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
{
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.
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.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char* replaceSubstring(char*,char*,char*);
char *string1, *string2, *string3;
string1 = "the dog jumped over the fence";
string2 = "the";
string3 = "that";
cout << replaceSubstring(string1,string2,string3);
}
char* replaceSubstring(char *original, char *from, char *to)
{
int origlen = strlen(original);
int i = 0;
int count = 0;
char *ptr;
while (i<origlen)
{
ptr = strstr(original+i, from);
if (!ptr)
break;
else
{
i = ptr - original + 1;
count++;
}
}
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
{
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.