Thursday 26 January 2012

Write a C program to delete n Characters from a given position in a given string.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
    char st[20],temp[20];
    int pos,i,j,ct=0,n;
    clrscr();
    printf("Enter the string:");
    gets(st);
    printf("\nEntre the index position:");
    scanf("%d",&pos);
    printf("\nEnter the no.of characters:");
    scanf("%d",&n);
    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' in 'temp' from a giv pos
                {
                    temp[j]=st[i];
                    i++;
                }
                temp[j]='\0';
                i=pos;
                //to delete the 'n' char and after restore the temp in st.
                for(j=0;temp[j]!='\0';j++)
                {
                    ct++;
                    if(ct>n)
                    {
                        st[i]=temp[j];
                        i++;
                    }
                }
                st[i]='\0';
            }
        }
        printf("\n\nAfter deletion the string: %s",st);
    }
    else
    printf("\nSorry, we cannot delete from that position.");
    getch();
}

No comments:

Post a Comment