I have to write some code for an assignment which finds a substring within a string.
Here is my code, and I added comments:
// the target is the substring that we want to find in the source string // m is the length of the target, and n is the length of the source int contains(char target[], int m, char source[], int n) { int flag = 0; // the source originally does not contain the target int i; // go through each character of the source string for(i = 0; i < n; i++) { int targetIndex = 0; int j; // check if the preceding characters of the source string are a substring // that matches the target string for(j = i; j < n && targetIndex < m; j++) { if(target[targetIndex] == source[j]) { flag = 1; targetIndex += 1; } else { flag = 0; // a letter does not match break; } } } return flag; }
So when I test this method, I always get 0 returned and I can't understand why.
If I try int i = contains("potatoes", 8, "toes", 4); it gives 0.
I've tried putting some print statements to see what character it matches, and it seems it only finds the first letter "t".
strstr(), I suggest you have a look at an implementation, e. g. the one in glibc.