Best way to replace a part of string by another in

2019-03-30 01:53发布

问题:

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!

回答1:

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;
}


标签: c string replace