Thursday 26 January 2012

Write a C program to insert a sub-string in to given main string from a given position.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
    char st[20],sub[10],temp[10];
    int pos, i, j;
    clrscr( );
    printf("Enter the main string:");
    gets(st);
    printf("\nEnter the substring to insert:");
    gets(sub);
    printf("Enter the index position:");
    scanf("%d",&pos);
    if(pos<=strlen(st))
    {
        for(i=0;i<=strlen(st);i++)
        {
            if(i==pos)
            {
                for(j=0;st[i]!='\0';j++) // to store the 'st' to 'temp' from given position.
                {
                    temp[j]=st[i];
                    i++;
                }
                temp[j]='\0';
                i=pos;
                for(j=0;sub[j]!='\0';j++) // to insert a sub-str to main string.
                {
                    st[i]=sub[j];
                    i++;
                }
                for(j=0;temp[j]!='\0';j++) // Lastly to insert the 'temp' to 'st' after sub-str.
                {
                    st[i]=temp[j];
                    i++;
                }
                st[i]='\0';
            }
        }
        printf("\nAfter adding the sub-string: %s",st);
    }
    else
    printf("\nSorry, it is not possible to insert a substring in that position.");
    getch();
}

No comments:

Post a Comment