P
pembed2003
Hi all,
I asked this question in the C group but no one seems to be interested
in answering it. :-( Basically, I wrote a search and replace function
so I can do:
char[] source = "abcd?1234?x";
char search = '?';
char* replace = "***";
char* result = search_and_replace(source,search,replace);
result will then be "abcd***1234***x". I understand that I can
probably use string instead of char* and there's probably some API in
the C++ standard library that I can use but I want to code it as an
exercise to learn the algorithm. Can someone suggest ways to improve
the performance of my search and replace algorithm? The function lacks
some error checkings but I am more interested in the algorithm.
Thanks!
char* search_and_replace(char* source,char search,char* replace){
char* result;
size_t l = strlen(source), r = strlen(replace), i, k;
int number_of_replaces = 0;
for(i = 0; i < l; i++){
if(source == search)
number_of_replaces++;
}
result = malloc((l - number_of_replaces) +
number_of_replaces * r + 1);
i = 0; k = 0;
while(k < l){
if(source[k] == search){
int j;
for(j = 0; j < r; j++){
result[i++] = replace[j];
}
}else{
result[i++] = source[k];
}
k++;
}
result = 0;
return result;
}
I asked this question in the C group but no one seems to be interested
in answering it. :-( Basically, I wrote a search and replace function
so I can do:
char[] source = "abcd?1234?x";
char search = '?';
char* replace = "***";
char* result = search_and_replace(source,search,replace);
result will then be "abcd***1234***x". I understand that I can
probably use string instead of char* and there's probably some API in
the C++ standard library that I can use but I want to code it as an
exercise to learn the algorithm. Can someone suggest ways to improve
the performance of my search and replace algorithm? The function lacks
some error checkings but I am more interested in the algorithm.
Thanks!
char* search_and_replace(char* source,char search,char* replace){
char* result;
size_t l = strlen(source), r = strlen(replace), i, k;
int number_of_replaces = 0;
for(i = 0; i < l; i++){
if(source == search)
number_of_replaces++;
}
result = malloc((l - number_of_replaces) +
number_of_replaces * r + 1);
i = 0; k = 0;
while(k < l){
if(source[k] == search){
int j;
for(j = 0; j < r; j++){
result[i++] = replace[j];
}
}else{
result[i++] = source[k];
}
k++;
}
result = 0;
return result;
}