Search This Blog

C Program to Replace First Occurrence of a Substring With Another String

In another post, i have wrote a c program to replace the last occurrence of a substring with another string within a given main string. (Click here for that program). Here, i am writing a  c program to replace the first occurrence of a string within another string. The program is as follows:
#include<stdio.h>
#include<string.h>

char* replaceFirst(char* mainstr,char * substr,char* newstr)
{
int lenmain,lensub,i,j,lennew,startindex=-1,limit,c;
lenmain=strlen(mainstr);
lensub=strlen(substr);
lennew=strlen(newstr);
char *result=(char*)malloc(sizeof(char)*(lenmain+100));
for(i=0;i<lenmain;i++)
    {
    if(lenmain-i>=lensub&&*(mainstr+i)==*(substr))
        {
        startindex=i;
        for(j=1;j<lensub;j++)
            if(*(mainstr+i+j)!=*(substr+j))
                {
                startindex=-1;
                break;
                }
        if(startindex!=-1)
            break;
        }
    }
limit=(startindex==-1)?lenmain:startindex;
for(i=0;i<limit;i++)
    *(result+i)=*(mainstr+i);
if(startindex!=-1)
    {
    for(j=0;j<lennew;j++)
        *(result+i+j)=*(newstr+j);
    c=i+lensub;
    i=i+j;
    for(;c<lenmain;c++,i++)
        *(result+i)=*(mainstr+c);
    }
*(result+i)='\0';
return result;
}

void main()
{
char a[100],sub[50],news[50];
printf("\nEnter original:");
gets(a);
printf("\nEnter sub string to be replaced:");
gets(sub);
printf("\nEnter new string to replace with:");
gets(news);
printf("\nresult:");
puts(replaceFirst(a,sub,news));
}

No comments: