例如,要验证有效的Url,我想执行以下操作
char usUrl[MAX] = "http://www.stackoverflow"
if(usUrl[0] == 'h'
&& usUrl[1] == 't'
&& usUrl[2] == 't'
&& usUrl[3] == 'p'
&& usUrl[4] == ':'
&& usUrl[5] == '/'
&& usUrl[6] == '/') { // what should be in this something?
printf("The Url starts with http:// \n");
}
Run Code Online (Sandbox Code Playgroud)
或者,我考虑过使用strcmp(str, str2) == 0,但这一定非常复杂.
是否有标准的C函数可以做这样的事情?
Ani*_*nge 35
bool StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
...
if(StartsWith("http://stackoverflow.com", "http://")) {
// do something
}else {
// do something else
}
Run Code Online (Sandbox Code Playgroud)
您还需要#include<stdbool.h>或只需更换bool与int
我建议这样:
char *checker = NULL;
checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
//you found the match
}
Run Code Online (Sandbox Code Playgroud)
这只会在字符串开头时才匹配,'http://'而不是像'XXXhttp://'
您也可以使用,strcasestr如果您的平台上可用.