Skip to main content

Replace String from another String in C

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>

int INDEX(char text[],char string[],int tlength,int slength)
	{
	int i,j,max,position=-1;
	max=tlength-slength+1;
	for(i=1;i<=max;i++)
		{
		if(position!=-1)
			{
			break;
			}
		for(j=0;j<slength;j++)
			{
			if(string[j]==text[i+j-1])
				{
				if(position==-1)
					{
					position=i;
					}
				}
			else
				{
				position=-1;
				break;
				}
			}
		}
	return (position);
	}

int DEL(char text[],int position,int s1length)
	{
	int tlength,i,j;
	tlength=strlen(text);
	for(i=position+s1length-1,j=position-1;i<tlength;i++,j++)
		{
		text[j]=text[i];
		}
	return (tlength-s1length);
	}

void INSERT(char text[],int position,int ntlength,char string2[])
	{
	int i,j,s2length;
	s2length=strlen(string2);
	for(i=ntlength-1;i>=position-1;i--)
		{
		text[i+s2length]=text[i];
		}
	for(i=0,j=position-1;i<s2length;i++,j++)
		{
		text[j]=string2[i];
		}
	for(i=0;i<ntlength+strlen(string2);i++)
		{
		printf("%c",text[i]);
		}
	}

void main()
	{
	clrscr();
	char text[30],string1[30],string2[30];
	int tlength,s1length,s2length,ntlength,position;

	printf("ENTER ORIGINAL TEXT:\t");
	gets(text);
	tlength=strlen(text);
	AGAIN:
	printf("\nENTER STRING TO BE REPLACE:\t");
	gets(string1);
	s1length=strlen(string1);
	printf("\nENTER STRING TO INSERTED:\t");
	gets(string2);
	s2length=strlen(string2);
	if(s1length>tlength)
		{
		printf("\n\aTHE TARGET STRING IS GERATER THAN ORIGINAL STRING");
		goto AGAIN;
		}
	position=INDEX(text,string1,tlength,s1length);
	if(position==-1)
		{
		printf("\n\aTHE TARGET IN NOT FOUND..! ");
		}
	else
		{
		ntlength=DEL(text,position,s1length);
		INSERT(text,position,ntlength,string2);
		}
	getch();
	}

Spread the love

Mashkawat Ahsan

I am Mashkawat Ahsan. Wikipedian, Mozillian, tech activist, art lover. Thank you for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *