Saturday 9 January 2016

Deleting Sub-string From A String. (Algoritmh 3.1)


Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.

/**Bismillahir Rahmanir Rahim.**/

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

int Index(char t[], char p[])
{
    int k=-1, r, s, max, l, m, cnt, i;
    s = strlen(t);
    r = strlen(p);
    max = s-r+1;
    for(i=0; i<max; i++)
    {
        if(t[i]==p[0])
        {
            for(l=1, cnt=1, m=i+1; l<r; l++, m++)
            {
                if(p[l]==t[m]) cnt++;
                else break;
            }
            if(cnt==r)
            {
                k = i;
                break;
            }
        }
    }
    return k;
}
char *DELETE(char t[], int k, int lnth)
{
    int i, j;
    for(j=k,i=0; t[j+lnth]; j++,i++)
        {
            t[j]=t[j+lnth];
        }

        t[j]='\0';
    return t;
}

int main()
{
    char *T=malloc(sizeof(char)*5000);
    char P[1000];
    int lnth_P, k;
    printf("Please, Input String.\n");
    gets(T);
    printf("Please, Input Sub-string Which You Want To Delete.\n");
    gets(P);
    lnth_P = strlen(P);
    for(k=Index(T,P); k!=-1; )
    {
        T = DELETE(T,k,lnth_P);
        k=Index(T,P);
    }
    printf("%s\n", T);
    free(T);
    return 0;
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.