Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*******************************************************************************
- Remove all the occurrences of string 2 from string 1. For example -
- ------Input
- string 1 : abcxyababccz
- string 2 : abc
- ------Output
- xyz
- length: 3
- *******************************************************************************/
- #include <stdio.h>
- // Function to find string length
- int length(char str[])
- {
- int len;
- for(len=0; str[len]!='\0'; len++);
- return len;
- }
- // Recursively removing string2 from string1
- void removeOccurrence(char str[], int i, int n)
- {
- str[i] = str[i+n];
- if(str[i+n]=='\0')
- return;
- removeOccurrence(str, i+1, n);
- }
- // function to find all the occurrences of string 2 in string 1
- void findOccurrence(char s1[], char s2[], int n1, int n2)
- {
- int i=0, j=1, flag, pos;
- while(i<n1)
- {
- /*
- break if length to be compared of string 1 is
- < the length of s2
- */
- if(n1-i < n2)
- break;
- if(s1[i]==s2[0])
- {
- flag = 0;
- for(j=1; j<n2; j++)
- {
- if(s1[i+j]!=s2[j])
- {
- flag = 1;
- pos = j; // storing the position where string didnt match
- break;
- }
- }
- // if flag is zero then s2 was found in s1 so remove it
- if(flag==0)
- {
- removeOccurrence(s1, i, n2);
- n1 = length(s1); // Updating the length of string 1
- i = 0;
- }
- else // s2 was not found in s1
- i += pos;
- }
- else
- i++;
- }
- }
- void main()
- {
- char str1[100], str2[100];
- int n1, n2;
- printf("Maximum String Length is 100!!!\n");
- printf("Enter String 1: ");
- gets(str1);
- printf("Enter String 2: ");
- gets(str2);
- n1 = length(str1);
- n2 = length(str2);
- // if n2 is greater then n1 cannot have occurrences of n2 in it
- if(n1>n2)
- {
- findOccurrence(str1, str2, n1, n2);
- printf("After removing Occurrences of String 2 from String 1\n");
- n1 = length(str1);
- printf("%s", str1);
- printf("\nLength: %d", n1);
- }
- else
- printf("Length of string 2 cannot be greater than that of String 1!\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement