Mental Jetsam

By Peter Finch

Replace a string with a character in C

Posted by pcfinch on June 26, 2008

This code is a simple string search and replace function in C/C++. It searches a NULL terminated string and replaces all the matching strings with a single character. For example, find all the occurrences of “&” is a string and replace them with “&”. The code is fast, as it only performs one single pass of the string. The code modifies the existing string, so care should be taken when using it, however, as the matched string can only ever be replaced with a single character the resulting string will never be larger that the original string, so it’s a pretty safe function.

void str_replace_c(char*pszString, char* pszMatch, char cTo)
{
  char* pStart = NULL ;
  char* pInMatch = pszMatch ;
  char* pInString = pszString ;
  char* pOutString = pszString ;
  char c ;

  if((pszString == NULL) ||
     (pszMatch == NULL) ||
     (*pszString == ''))
    return ;

  do {
    c = *(pInString++) ;
    if(pStart == NULL) {
      if(c == *pszMatch) {
        pStart = pOutString ;
        pInMatch = pszMatch + 1 ;
      }
    } else {
      if(*pInMatch == '') {
        pOutString = pStart ;
        *(pOutString++) = cTo ;
        pStart = NULL ;
      } else {
        if(*pInMatch == c)
          pInMatch++ ;
        else
          pStart = NULL ;
      }
    }
    *(pOutString++) = c ;
  } while(c != '') ;
}

int main()
{
  char in[] = "& amp; This is & amp; a test & amp;" ;
  str_replace_c(in, "& amp;", '&') ;
  printf("out=\"%s\"\n", in) ;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: