The following is the code that implements the string substitution function in the C language:
Char *replace (char *source, Char *sub, char *rep)
{
Char *result;
/*PC1 is the scan pointer copied to result results.
/*PC2 is the auxiliary pointer to scan source.
/*PC3 looking for substrings, check to see if the change source is equal to the substring and is the scan pointer to the sub.
/* Find the match, in order to copy to the result string, is pointing to the rep scan pointer.
Char *PC1, *PC2, *PC3;
int ISource, isub, Irep;
Isub = strlen (sub); /* The length of the contrast string * *
Irep = strlen (Rep); /* The length of the replacement string * *
Isource= strlen (source); /* The length of the source string * *
if (NULL = = *sub)
return strdup (source);
/* The required space for the application result string * *
result = (char *) malloc ((Irep > Isub)? (float) strlen (source)/isub* irep+ 1:isource) * sizeof (char));
PC1 = result; /* Prepare for PC1 to copy each byte of the result string sequentially.
while (*source!= NULL)
{
/* To check whether the source and sub are equal to prepare, for PC2,PC3 to assign initial value * *
PC2 = source;
PC3 = Sub;
/* Out of circulation (any) conditions are:
* *PC2 Not equal to *PC3 (not equal to substring)
* PC2 to end of source string
* PC3 to the end of the source string (at this point, all substrings are checked, source is equal to sub)
*****************************************************/
while (*PC2 = = *PC3 && *pc3!= null && *PC2!= null)
pc2++, pc3++; [Page]
/* If a substring is found, do the following processing work * *
if (NULL = = *PC3)
{
PC3 = rep;
/* Append the substitution string to the result string/*
while (*PC3!= NULL)
*pc1++ = *pc3++;
pc2--;
Source = PC2;
/* check source and sub equal loop after end,
* PC2 The corresponding position is the string terminator in the sub. This is the next position in the source string.
* Point Source to one of the preceding characters.
***************************************************/
}
else/* If no substring is found, copy the byte from source to the result string.
*pc1++ = *source;
source++; /* Move source Backward one character/*
}
*PC1 = NULL;
return result;
}
The following is the test code:
int main()
{
char s1[] ="abbccdfdcdbbdcd";
char s2[]="dcd";
char s3[]="12345";
char *p = replace(s1,s2,s3);
printf("source=%s\n",s1);
puts(s1);
printf("sub = %s\n",s2);
puts(s2);
printf("replace string = %s",p);
return 0;
}