c - 如果第二个字符串在开头,strstr 会返回与第一个字符串相同的指针吗?

标签 c string substring c-strings strstr

基本上,我需要查明字符串是否以 [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 .

最佳答案

是的,检查 if (message != urlStart) 将按预期工作,假设 message[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

关于c - 如果第二个字符串在开头,strstr 会返回与第一个字符串相同的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37016931/

相关文章:

c - 地址和推送指令前的星号,它被推送到哪里?

c - 用C读取二进制文件

c++ - 为什么utf8中的两个字符串比较不正确?

javascript - 递归地从html中删除空节点

python - 使用多个分隔符在 python 中拆分字符串的最佳方法 - 同时保留分隔符

c# - String.Substring() 似乎是这段代码的瓶颈

C 程序链接错误?

c - C中结构中的字符串数组

c - 如何在C中的字符串末尾添加 "\n"

php - 向仅包含数字的日期字符串添加斜杠