8

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!

Community
  • 1
  • 1
nikhilthecoder
  • 301
  • 1
  • 3
  • 12
  • ya, but there also no clean simple code is there. :( – nikhilthecoder Nov 15 '11 at 14:08
  • Also very simple and basic in C++, but C is C, right? :) Anyway, first answer on that question describes how exactly to do it. – Kos Nov 15 '11 at 14:18
  • Exactly, I cant describe my love for C! :D That is very long. My idea was to shift the characters to right or left by the difference in length of the two sub strings, and then insert the new sub string in place, but I am not being able to do it, without using a fixed char array. :( – nikhilthecoder Nov 15 '11 at 14:29

1 Answers1

4

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;
}
Tudor
  • 61,523
  • 12
  • 102
  • 142
  • The solution given in this one considers only the first occurence of the original sub string. I want to do it to some perticular occurence of the sub string. – nikhilthecoder Nov 15 '11 at 14:34
  • You mean like replacing only the 5th occurrence for example? – Tudor Nov 15 '11 at 14:39
  • yes, for simplicity we can have the position in the string from where we need to look for the very next occurrence and replace it. – nikhilthecoder Nov 15 '11 at 14:43
  • 1
    Well then just add a new parameter to the function presented in that link. Then copy to another temporary string from that position on of the original string and then execute the rest of the code on the temporary string. – Tudor Nov 15 '11 at 14:50
  • My idea was to shift the characters to right or left by the difference in length of the two sub strings, and then insert the new sub string in place, but I am not being able to do it, without using a fixed char array – nikhilthecoder Nov 15 '11 at 14:51