P
pembed2003
Hi all,
I need to write a function to search and replace part of a char*
passed in to the function. I came up with the following:
char* search_and_replace(char* source,char search,char* replace){
char* result;
size_t l = strlen(source), r = strlen(replace), i;
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;
while(i < l){
if(source == search){
int j;
for(j = 0; j < r; j++){
result = replace[j];
i++;
}
}else{
result = source;
i++;
}
}
result = 0;
return result;
}
later I can then use it like:
char source[] = "1234?5678?9";
char search = '?';
char* replace = "***";
char* result = search_and_replace(source,search,replace);
free(result);
and I will end up result being "1234***5678***9"
Other than the lack of some error checkings, the above function seems
to work ok but looks like it's doing alot of work. Can you think of
anyway to improve the speed of the function?
Thanks!
I need to write a function to search and replace part of a char*
passed in to the function. I came up with the following:
char* search_and_replace(char* source,char search,char* replace){
char* result;
size_t l = strlen(source), r = strlen(replace), i;
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;
while(i < l){
if(source == search){
int j;
for(j = 0; j < r; j++){
result = replace[j];
i++;
}
}else{
result = source;
i++;
}
}
result = 0;
return result;
}
later I can then use it like:
char source[] = "1234?5678?9";
char search = '?';
char* replace = "***";
char* result = search_and_replace(source,search,replace);
free(result);
and I will end up result being "1234***5678***9"
Other than the lack of some error checkings, the above function seems
to work ok but looks like it's doing alot of work. Can you think of
anyway to improve the speed of the function?
Thanks!