This function returns the number of substitutions and a new string with
All replacements made to the original string.


/***
	INPUT
		source : string to evaluate
		find : string to search
		substitute : string to substitute
	OUTPUT
		dest : new destination string
	RETURN
		number of subtutions
****/
char Replace(char* source, char* dest, char* find, char* substitute)
{
	char occur,loop,*ret;
	int position,lenf,lens,m;
	lenf=strlen(find);
	lens=strlen(substitute);
	occur=0;
	loop=1;
	m=0;
	position=0;
	dest[0]=0;

	while(loop)
	{
		ret=strstr(source,find);//find occurrence
		if (ret!=NULL)
		{
			position=ret-source;//position of substring
			strncpy(dest+m,source,position);//copy left string
			m=m+position;
			dest[m]=0;
			strcat(dest,substitute);//concatenate replaced string
			m=m+lens;
			source=ret+lenf;//new position to search is after old finded string
			occur++;
		}
		else
		{
			strcpy(dest+strlen(dest),source);
			loop=0;
		}
	}
	return occur;
}

char testreplace()
{

	char s[150],d[150];
	char f[50],su[50];
	char num;
	strcpy(s,"The difference between stupidity and genius is that genius has its limits. [A.E.]");
	printf("Original string \n%s\n",s);
	strcpy(f,"genius");
	strcpy(su,"intelligent");
	num=Replace(s,d,f,su);
	printf("Number of replacements %d\nReplaced string \n%s\n",num,d);
}

 

Advertisements