1. You are overwriting the "success" return value with a "fail" return value every single time you see a ptn[0] character in the string. You need to stop looping and return as soon as you get a "success".
2. First loop is going too far. It should stop at len(src) - len(ptn).
3. In the inner loop, you must wait until you've checked the ENTIRE pattern before you set match=0; (and then return immediately as per #1).
4. If there is a mismatch in the pattern vs source, the inner loop should exit immediately, and not check any more characters.
5. This loop structure is a LOT slower than it could be. Precalculate the len()s. Use the pointers, and not indexes. Count your loops down to 0, and not up to n.
Hmmm.. not sure if you see what I am doing here; maybe, but just in case here it is:
1. I loop the length of source: the red dog rows quickly
2. I then check within that loop if we find a match with the first character of pattern: (r)ows
3. If I find a match, I loop the length of pattern: rows
4. If all match then match will never be 1, else it becomes 1
5. I check if match is 0, if so, return 0, else keep looking
6. If match never becomes 0, it must be false so return 1
The only thing I can think of that it could fail is on number 3, where I could be failing once I hit that space behind it: rows_ <-- fails here, so it would be me overwriting my match=0, with match=1 which would return 1 and fail. I think I will do what you said in the inner for loop (count down to zero, that way I can't shoot past my mark on accident, and I will also pre-calculate the length for speed. I'll let you know what happens. thanks
Free energy is indeed evil for it absorbs the light.
printf(0x0F,1,1,"(rowz) - Return = %d", inString("The red dog rows quickly","rowz"));
printf(0x0F,1,2,"(rows) - Return = %d", inString("The red dog rows quickly","rows"));
produces this:
(rowz) - Return = 1
(rows) - Return = 0
beautiful. thanks
EDIT: grrr.. I just tested that and you are right. This is annoying. Be right back.
//*******************************
//Find the position of a string within a string
//Return: Position of first char of pattern,
//else if no match the return is -1.
//*******************************
int strpos(const void *source, const void *pattern)
{
int i=0;
int x=0;
int match=1;
int pos;
const char *src = (const char*) source;
const char *ptn = (const char*) pattern;
int slen=len(src);
int plen=len(ptn);
for(i=0;i<slen;i++)
{
if(src[i]==ptn[0])
{
for(x=0;x<plen;x++)
{
if(src[i+x]==ptn[x])
{
match=0;
pos=i;
} else {
match=1;
pos=0;
break;
}
}
}
if(match==0)
{
return pos+1;
}
}
return -1;
}