C:帮助与自定义strpos()函数
问题描述:
我有以下功能:C:帮助与自定义strpos()函数
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
循环正确地分成多行?接受的方式是什么?
编辑:strlen()
自然是一个自定义函数,它返回字符串的长度。这工作正常。
答
的解决方案是标准的一声,你的头抵墙式功能于一个无限循环的 - 难怪 - 为什么 - 这是地狱 - 你是一个程序员。
if(temp == *needle+nePos)
应该是:
if(temp == *(needle+nePos))
答
每次绕着循环,你都会从干草堆中得到下一个字符。因此,如果在您将针与干草堆的子字符串从位置0开始进行比较之后,针具有两个字符,则草垛指针指向位置2(针对两字符针)。
这意味着你跳过与草垛子比较针的位置开始1
最差。码。永远。 – Myforwik 2010-12-02 11:28:29
这是作业吗,还是我们真的获得奖励代表回答奖金问题? – MAK 2010-12-02 11:29:59