Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

General purpose string substitute function anyone? 1

Status
Not open for further replies.

mjosborne

Programmer
Nov 19, 2002
3
AU
Hi,
Does anyone have a general purpose C string substitute function . I have tried it with strtok but failed.
The function could be of the form
char *sub_string(char *the_string, char *find, char *replace);
returning a string with the substitution of find for replace.

eg. char *str = "The quick brown fox";
char *new_str = "";

new_str = sub_string(str, "fox", "dog");
 
Figured it out myself....
char *sub_line( char *str, char *find, char *repl)
{
char *ptok;
char *new = NULL;
char *theRest = NULL;
int got_token = 0;
int posn=0;

new = (char *) malloc(MAX_LINE);
if (str == NULL)
{
return(str);
}
strcpy(new,str);
ptok = strstr(str, find);
while (ptok != NULL)
{
got_token = 1;
theRest = (ptok+strlen(find));
posn=strlen(new) - strlen(ptok);
for (i=0; i< strlen(find); i++)
new[i+posn] = repl;
strcat(new,theRest);
ptok = strstr(theRest, find);

}
if (! got_token)
return(str);

return(new);
}
 
This may not work any different, but it'll probably be more efficient and certainly easier to follow IMHO.

#include <stdlib.h>
#include <string.h>

char *s(const char *str, const char *replace, const char *with)
{
char *rp;
char *pos;
size_t bufsiz;

if ((pos = strstr(str, replace)) == NULL)
return NULL;

bufsiz = strlen(str) - strlen(replace) + strlen(with);
if ((rp = calloc(bufsiz + 1, sizeof *rp)) == NULL)
return NULL;

strncpy(rp, str, pos - str);
strcat(rp, with);
strcat(rp, pos + strlen(replace));

return rp;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top