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() 自然是一个返回字符串长度的自定义函数。这工作正常。
I have the following function:
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;
}
It works properly when I search for a single character:
printf("Strpos: %d\n", strpos("a", "laoo")); // Result: "Strpos: 1"
But it improperly with longer string:
printf("Strpos: %d\n", strpos("ao", "laoo")); // Result: "Strpos: -1"
What is the problem?
Bonus question: is the while
loop properly broken into multiple lines? What is the accepted way to do this?
EDIT: strlen()
is, naturally, a custom function that returns the length of the string. This works properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次循环时,您都会从干草堆中获得下一个字符。因此,如果当您完成将 Needle 与 haystack 中从位置 0 开始的子字符串进行比较时,needle 已经有两个字符,则 haystack 指针将指向位置 2(对于两个字符的 Needle)。
这意味着您跳过将 Needle 与 haystack 中从位置 1 开始的子字符串进行比较。
Each time you go round the loop you get the next character from haystack. So if needle has two characters by the time you have finished comparing needle with the substring of haystack beginning at position 0, the haystack pointer is pointing at position 2 (for a two character needle).
This means that you skip comparing needle with the substring of haystack beginning at position 1.
解决方案是标准的无限循环中用头撞墙并想知道为什么你是一名程序员的类型。
应该是:
The solution is of the standard bang-your-head-against-the-wall-in-an-infinite-loop-and-wonder-why-the-hell-you're-a-programmer variety.
Should be: