私は次の機能を持っています:
int strpos(const char *needle, const char *haystack)
{
int neLen, haLen, foundPos, nePos, i;
char temp;
neLen = strlen(needle);
haLen = strlen(haystack);
if(haLen < neLen)
return -1;
nePos = 0;
foundPos = -1;
i = 0;
while((temp = *haystack++) != '\0'
&& (i < (haLen-neLen+1) || foundPos > -1)
&& nePos < neLen)
{
if(temp == *needle+nePos)
{
if(nePos == 0)
foundPos = i;
nePos++;
}
else
{
nePos = 0;
foundPos = -1;
}
i++;
}
return foundPos;
}
単一の文字を検索すると、正しく機能します。
printf("Strpos: %d\n", strpos("a", "laoo")); // Result: "Strpos: 1"
しかし、それはより長い文字列では不適切です:
printf("Strpos: %d\n", strpos("ao", "laoo")); // Result: "Strpos: -1"
何が問題ですか?
おまけの質問: ループはwhile
適切に複数の行に分割されていますか? これを行うための受け入れられた方法は何ですか?
EDIT:strlen()
当然、文字列の長さを返すカスタム関数です。これは正常に動作します。