Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to replace a part of string by another in c? [duplicate]

Tags:

c

string

replace

Possible Duplicate:
how to replace substring in c?

I have tried looking for a better solution for this problem. There are codes available but all for C++. Not to forget this is very simple and basic in Java. I wanted a great optimal solution in C?

Any help will be greatly appreciated! Thanks!

like image 273
nikhilthecoder Avatar asked Nov 15 '11 13:11

nikhilthecoder


1 Answers

Simple solution found on google: http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/

Edit: Taking your specification into account, I've edited the code in the link to this:

char *replace_str(char *str, char *orig, char *rep, int start)
{
  static char temp[4096];
  static char buffer[4096];
  char *p;

  strcpy(temp, str + start);

  if(!(p = strstr(temp, orig)))  // Is 'orig' even in 'temp'?
    return temp;

  strncpy(buffer, temp, p-temp); // Copy characters from 'temp' start to 'orig' str
  buffer[p-temp] = '\0';

  sprintf(buffer + (p - temp), "%s%s", rep, p + strlen(orig));
  sprintf(str + start, "%s", buffer);    

  return str;
}
like image 141
Tudor Avatar answered Nov 14 '22 22:11

Tudor