练习5-4编写函数
strend(s,t),如果字符串t发生在字符串s的末尾,则返回一个函数,否则返回零。
#include <stdio.h>
int str_end(const char *, const char*);
int main(void)
{
char *s1 = "Man is a rope stretched over an abyss.";
char *s2 = "an abyss.";
printf("%s\n", str_end(s1, s2) ? "Yes" : "No");
return 0;
}
int str_end(const char *s, const char *t)
{
const char *init = t; /* Hold the initial position of *t */
while (*s) {
while (*s == *t) {
if (!(*s)) {
return 1;
}
s++;
t++;
}
s++;
t = init;
}
return 0;
}发布于 2014-06-19 16:21:25
一个更简单的方法是从结尾开始,而不是从头开始。
int str_end(const char *s, const char *t)
{
if (strlen(s) < strlen(t)) return 0;
return 0 == strcmp(&s[strlen(s)-strlen(t)], t);
}为了避免调用strlen比需要的更多,这段代码要稍微快一些:
int str_end(const char *s, const char *t)
{
int diff = strlen(s)-strlen(t);
return diff > 0 && 0 == strcmp(&s[diff], t);
}发布于 2014-06-19 15:52:52
不幸的是,您的代码有一个错误。如果末端字符串有错误匹配,则回滚指向init值的尾字符串指针。您还应该回滚s字符串中的指针,以便在失败的匹配过程中查找实际结果部分启动的情况。
用一个例子来描述这一点比较容易。考虑一下无意义的输入值:
人是人
加上搜索短语:
男子汉
文本以an man结尾,但是您的代码会说没有。这里有一个想法,说明了这个问题。
您需要追溯您的文本指针以及搜索指针。
另外,在其他新闻中,变量名s和t并不是很有描述性,因此很难简单地阅读代码。考虑一下像text和search这样的名字,或者描述变量是什么的东西……
发布于 2014-06-19 16:12:35
我正要说,我在试图了解您的逻辑如何工作时,发现了以下测试用例中的一个bug:
char *s1 = "an abyssan abyssan abyssan abyss.";
char *s2 = "an abyss.";
char *s1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.";
char *s2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa.";我认为您应该从编写测试用例开始,并检查代码是否生成您期望的结果。
举个例子,这是我写的。我不会说它没有bug,因为我没有花太多时间在上面,但至少我有一点信心,因为它似乎通过了我编写的不同的测试:
#include <stdio.h>
#include <assert.h>
int str_end(const char *s, const char *t)
{
// Going forward on both strings til we reach an end
int l;
for (l=0; *s && *t; s++, t++, l++);
// If t is not over ...
if (*t)
{
// ... then s should be
assert(!*s);
// so s is shorter and there is no point in going further
return 0;
}
assert(!*t);
// Going forward on s
for ( ; *s; s++);
// Going backward on both -- this could also be done with a normal string comparison function by going back l steps and comparing remaining strings
for ( ; l>=0; l--, s--, t--)
if (*s != *t)
return 0;
return 1;
}
int main(void)
{
assert( str_end("Man is a rope stretched over an abyss.", "an abyss."));
assert(!str_end("Man is a rope stretched over an abyss.", "un abyss."));
assert( str_end("Man is a rope stretched over an abyss.", ""));
assert( str_end("", ""));
assert( str_end(".", "."));
assert( str_end(".", ""));
assert(!str_end("", "."));
assert( str_end("qqqqqqqqqqqqqqqqqqqqqqqqqq", "qq"));
return 0;
}https://codereview.stackexchange.com/questions/54722
复制相似问题