Mental Jetsam

By Peter Finch

Archive for June 26th, 2008

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

Posted in C++/MFC | Leave a Comment »