C Program to Find Substring Of String Without Using Library Function !!!
Program : C Program to find substring
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include<stdio.h> #include<string.h> int search(char[], char[]); int main() { int loc; char source[] = "maharashtra"; char target[] = "sht"; loc = search(source, target); if (loc == -1) printf("\nNot found"); else printf("\nFound at location %d", loc + 1); return (0); } int search(char src[], char str[]) { int i, j, firstOcc; i = 0, j = 0; while (src[i] != '\0') { while (src[i] != str[0] && src[i] != '\0') i++; if (src[i] == '\0') return (-1); firstOcc = i; while (src[i] == str[j] && src[i] != '\0' && str[j] != '\0') { i++; j++; } if (str[j] == '\0') return (firstOcc); if (src[i] == '\0') return (-1); i = firstOcc + 1; j = 0; } } |
Explanation Of Program :
If you look at the above program then you will find this program approach bit difficult but still it is perfect program.
Step 1 : Accepting the Input
Accepting input is state forward step.
1 2 |
char source[] = "maharashtra"; char target[] = "sht"; |
Step 2 : Calling Function and Passing Parameters
We are calling user defined function , Consider following strings are entered by the user –
1 2 |
char source[] = "maharashtra"; char target[] = "sht"; |
Step 3 : Function Definition :
We are iterating inside while loop upto end of string. Variable ‘i’ is used to iterate String 1.
1 |
while (src[i] != '\0') { |
We are searching String 2 in String 1 so we are checking whether First Character of String 2 is present inside String 1 or not.
1 2 |
while (src[i] != str[0] && src[i] != '\0') i++; |
We are moving inside String 1 as we don’t find first character of String 2 in String 1. The while loop will be terminated because of two conditions i.e End of String 1 or Character Found.
If above while loop is terminated because of coinsurance of End Character then we can say that String2 is not a Substring of String1.
1 2 |
if (src[i] == '\0') return (-1); |
Save Value of ‘i’ inside another value to track first occurrence of Substring. Now we are checking whether all characters from string2 are present inside string1 or not.
1 2 3 4 |
while (src[i] == str[j] && src[i] != '\0' && str[j] != '\0') { i++; j++; } |
Now again above loop can be terminated using 3 conditions –
- End of String 1
- End of String 2
- Characters are unequal
If Loop gets terminated due to end of string2 then we can say that string2 is substring of string1.