Link to home
Start Free TrialLog in
Avatar of cpix
cpix

asked on

Replace a string, in a string function

Im wondering if anyone could please show me how
to create a

char *strreplace(oRgLine, srcWord, newWord )
which will replace all occurences srcword with newword in orgline.

Avatar of imladris
imladris
Flag of Canada image

HMmmm. The general case is probably going to be quite messy. If you have to deal with a newWord that can be more characters than the srcWord, then you would either have to guarantee that oRgLine "has" sufficient memory to contain the new expanded string (and relying on the caller to do that is not ideal), or you have allocate a buffer to hold the new string (and then you have to rely on the caller to free it; also not ideal).

Do you need the general case? Or are there some limitations/assumptions/specifications about what parameters the caller will be handing in.
Avatar of cpix
cpix

ASKER

the newWord is fixed (fixed length), so are the srcWord, and in this case it's simple to calculate how many chars that are added to the string, since I know how many words it needs to change. (even though it wont be the most ideal way to do it).

Avatar of cpix

ASKER

the newWord is fixed (fixed length), so are the srcWord, and in this case it's simple to calculate how many chars that are added to the string, since I know how many words it needs to change. (even though it wont be the most ideal way to do it).

Avatar of cpix

ASKER

Ok, I got it working, but for everyone else who wants to know how to do this, this is it :-)


char *ReplaceString(char *innString, char *forekomst, char *nyforekomst, const int strlength)
{
  char *resString;
  char *resString2;

  char *newstring;
  char *inStr;

  inStr = (char *)malloc(strlength);
  newstring = (char *)malloc(strlength);
  resString = (char *)malloc(strlength);
  resString2 = (char *)malloc(strlength);
  strcpy(inStr, innString);
  while (1)
    {
      if (strstr(inStr, forekomst) != NULL)
        {
          strcpy(newstring, strstr(inStr,forekomst));
          strcpy(resString, &newstring[7]);
          strncpy(resString2, inStr, strlen(inStr)-strlen(newstring) );

          strcat(resString2, nyforekomst);
          strcat(resString2, resString);


          memset(inStr,0,strlength);
          memset(resString,0,strlength);
          memset(newstring, 0, strlength);
          memcpy(inStr, resString2, strlength);
          memset(resString2,0, strlength);

        }else
          {
            break;
          }
    }
 
  return inStr;
  free(inStr);
  free(resString);
  free(resString2);
  free(newstring);
}

-- cPix.
ASKER CERTIFIED SOLUTION
Avatar of akshayxx
akshayxx
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cpix

ASKER

Just to end the thread :)