Saturday 20 July 2013

17. Write a C++ program that uses functions to perform Insert a sub-string into the given main string from a given position and Delete n characters from a given position in a given string.

#include<iostream.h>
#include<string.h>
void del(char s[],int r,int c);
void substring(char s[],char m[],int n)
{
        char ans[100];
        int i,u,t;
        if(n>strlen(s))
        {
          cout<<"Position is Out of the String bound \n Insert failed"<<endl;
          return ;
        }
        for(i=0;i<n;++i)                 //copy the string upto the starting position
        {
                ans[i]=s[i];
        }
        for(i=0;i<strlen(m);++i)   //now copy the sub string into temp array
        {
                t=n+i;
                ans[t]=m[i];
        }
        u=n+strlen(m);
        for(i=n;i<strlen(s);++i)    //finally copy the remaining main string
        {
                ans[u]=s[i];
                ++u;
        }
        ans[strlen(s)+strlen(m)]='\0';  //Adding Null terminator to temp array
        cout<<"New string is :";
        puts(ans);
}

int main()
{
        char s[100],m[50],ch;
        int r,c,i,n;
        cout<<"\nenter a string"<<endl;   //Reading main String
        cin>>s;
        cout<<"enter 'd' for deletion\n\t 'i' for insertion : ";
        cin>>ch;                                            //Reading choice
        switch(ch)
        {
        case 'd':
        cout<<"\nenter the starting position for deletion";
        cin>>r;
        cout<<"\nenter the number of char want to del";
        cin>>c;
        del(s,r,c);                                              //calling del function
        break;
        case 'i':
        cout<<"enter the string m";         //reading Sub string
        cin>>m;
        cout<<"enter the position ";         //Reading starting position
        cin>>n;
        substring(s,m,n);                         //calling sub string function
        break;
        default:
        cout<<"Invalid choice";
        }
        return 0;
}

void del(char s[],int r,int c)
{       char a[100];
        int i,l;
        for(l=0;s[l]!='\0';l++);          //finding the size of main string
        if((r+c)>l)
        cout<<"deletion  is running out of given string\nso deletion impossible";
        else
        {
                for(i=0;i<r;++i)
                a[i]=s[i];
                for(i=(r+c);i<l;++i,++r)
                a[r]=s[i];
                a[l-c]='\0';
        }
        cout<<"string after deletion :"<<a;
}

1 comment: