Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int find (char string[],char sub[]); //returns array position of first time substring is found
- int findFrom(char string[],char sub[],int n); //returns array position of first time substring is found STARTING FROM n index position of main string.
- int main()
- {char string[200], sub[200], ch;
- int i, index = -5;
- printf("Enter the main string \n");
- gets(string);
- printf("Enter the substring: ");
- gets(sub);
- index = find(string, sub);
- if (index < 0)
- printf("Substring not found");
- else
- printf("Substring first found in %d position of the string",index+1);
- return 0;
- }
- int find (char string[],char sub[])
- {int i, j = 0, k;
- char ch;
- for (i = 0; string[i]!= 0; i++)
- {
- if (string[i] == sub[j])
- { k = i;
- while(sub[j]!=0)
- {
- if (string[k++] != sub[j++])
- break;
- }
- if (sub[j] == 0)
- {
- return i; //a confirmed match has been found.
- }
- else
- {
- j = 0;
- }
- }
- }
- return -1;
- }
- int findFrom(char string[],char sub[],int n)
- {
- int i, j = 0, k;
- char ch;
- for (i = n; string[i]!= 0; i++)
- {
- if (string[i] == sub[j])
- { k = i;
- while(sub[j]!=0)
- {
- if (string[k++] != sub[j++])
- break;
- }
- if (sub[j] == 0)
- {
- return i; //a confirmed match has been found.
- }
- else
- {
- j = 0;
- }
- }
- }
- return -1;
- }
- //
- Second code
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int findFrom(char string[],char sub[]); //returns array position of first time substring is found STARTING FROM n index position of main string.
- int main()
- {char string[200], sub[200], ch;
- int i, index = -5, n = 0;
- printf("Enter the main string \n");
- gets(string);
- printf("Enter the substring: ");
- gets(sub);
- for (i = 0; string[i]!= 0; i++)
- {
- index = findFrom(string + n,sub);
- if (index > 0)
- {
- printf("%d ",index+n);
- i = index;
- n = index + n;
- }
- index = -1;
- }
- if (n == 0)
- printf("String not found.");
- }
- int findFrom(char string[],char sub[])
- {
- int i, j = 0, k;
- char ch;
- for (i = 0; string[i]!= 0; i++)
- {
- if (string[i] == sub[j])
- { k = i;
- while(sub[j]!=0)
- {
- if (string[k++] != sub[j++])
- break;
- }
- if (sub[j] == 0)
- {
- return i; //a confirmed match has been found.
- }
- else
- {
- j = 0;
- }
- }
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement