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