Search This Blog

C Program to Replace All Occurrences of a Substring with Another String

After the c programs to replace first occurrence of substring and last occurrence of substring, i am posting a c program to replace all the occurrences of a given substring inside the original string.

You may also see:
C Program to Replace First Occurrence of a Substring With Another String
C Program to Replace Last Occurrence of a Substring With Another String

Here also, i have written a function which takes three parameters (the main string, the substring to be replaced and the substring to replace with). The function return a string with all the occurrences of the substring replaced with the specified string. The program uses pointer for manipulating the strings. The program is as follows:


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

char* replaceAll(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+200));
for(c=0,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)
            {
            for(j=0;j<lennew;j++,c++)
                {
                *(result+c)=*(newstr+j);
                }
            i=i+lensub-1;
            }
        else
            {
            *(result+c)=*(mainstr+i);
            c++;
            }
        }
    else
        {
        *(result+c)=*(mainstr+i);
        c++;
        }
    }
*(result+c)='\0';
return result;
}

void main()
{
char a[300],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(replaceAll(a,sub,news));
}

No comments: