Sunday, 14 August 2016

Delete all occurrences of pattern from a string

Delete all occurrences of pattern (pat) from a string (txt)


#include<stdio.h>
#include<string.h>
void main()
{
                char txt[30],  pat[30];
                int m, n;
                int i, j, found = 0;
                printf("\nEnter the main string:");
                gets(txt);
                printf("\nEnter the pattern to be searched: ");
                gets(pat);
                m = strlen(txt);
                n = strlen(pat);

                for(i=0;  i<=m-n;  i++)
                {
                                found  = 1;
                                for(j=0; j<n; j++)
                                {
                                                if(txt[i+j] != pat[j])
                                                {
                                                                found = 0;
                                                                break;
                                                }
                                }
                                if(found == 1)
                                {
                    /* If pattern is found then shift all characters to left and decrement the string length */
                                                for(j=i;  j<m -n; j++)
                                                {
                                                                txt[j] = txt[j+n];
                                                }
                                                txt[j] = '\0';
                                                m = m - n;
                                 }
                }
                if(found == 0)
                                printf("\nPattern not found");
                else
                {
                                printf("\nAfter deleting pattern the string is: ");
                                puts(txt);
                }
}

Output:
Enter the main string:    hello hii how hii
Enter the pattern to be searched:   hii
After deleting pattern the string is: hello    how


Enter the main string:    hello hii how hii
Enter the pattern to be searched: abc

Pattern not found