Search This Blog

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

Functions to play with strings are very useful. I have wrote a program to replace first occurrence of a substring inside another string. (Click here for that program). Here i write a function in c to replace the last occurrence of a substring in a given string with the given new string. The function written in c, takes three arguments; the main string, the substring which is to be replaced and the new new string to replace with. I have written a full c program with main function to test the working of the c program. The function simply finds the last occurrence of the substring in the main string and replaces it with the new string (third parameter). The program is as follows:

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

char* replaceLast(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=lenmain-1;i>=0;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(replaceLast(a,sub,news));
}


No comments: