【问题标题】:Will strstr return the same pointer as the first string if the second string is at the beginning?如果第二个字符串在开头,strstr 会返回与第一个字符串相同的指针吗?
【发布时间】:2016-05-04 01:25:42
【问题描述】:

所以基本上,我需要找出一个字符串是否以[URL] 开头并以[/URL] 结尾。

我现在正在做:

const char *urlStart;
// ...
urlStart = strstr(message, "[URL]");
if (urlStart == NULL) {
    urlStart = strstr(message, "[url]");
}

if (urlStart == NULL) {
    return NULL;
}

根据cplusplus.com,“指向str2中指定的整个字符序列的str1中第一次出现的指针”。

这是否意味着我可以做到这一点?

/*
 * If the pointer to message is the same as urlStart,
 * message begins with urlStart
 */
if (message != urlStart) {
    return NULL;
}

// URL starts 5 characters after [URL]
urlStart += 5;

初步测试似乎表明这不起作用。

完整的函数位于here

【问题讨论】:

  • NULL + 5 永远不会等于 NULL。换句话说,你需要先检查来自strstr 的返回值,然后再对其进行数学运算。
  • @user3386109 感谢您指出这一点!最初我的代码是strstr(message, "http://"),所以我不需要将指针增加 5 个字符。
  • 是的,现在代码可以工作了。认为这个问题值得保留@user3386109?
  • 我刚刚取消删除了@user3386109 的问题。我可能很快就会切换用户帐户。

标签: c string substring c-strings strstr


【解决方案1】:

是的,检查 if (message != urlStart) 将按预期工作,假设 message[URL][url] 开头。但是,例如,如果message[Url] 开头,那么strstr 将因为大小写不匹配而找不到该字符串。

鉴于您要求字符串位于message 中的已知位置,strstr 函数对您的作用并不大。只检查message的前5个字符就更简单了,像这样

char *start = "[URL]";
for ( int i = 0; i < 5; i++ )
    if ( toupper(message[i]) != start[i] )
        return NULL;

你可以像这样检查最后的[/URL]

length = strlen(message);
if ( length < 12 )
    return NULL;

char *end = "[/URL]";
for ( int i = 0; i < 6; i++ )
    if ( toupper(message[length-6+i]) != end[i] )
        return NULL;

您也可以使用不区分大小写长度限制的字符串比较,但请注意,这些比较不可移植。我相信它在 Windows 上是 strnicmp,在 unix 克隆上是 strncasecmp

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 2019-09-17
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2016-03-29
    相关资源
    最近更新 更多