C语言 如何检查字符串是否以C中的某个字符串开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15515088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if string starts with certain string in C?
提问by J. Berman
For example, to validate the valid Url, I'd like to do the following
例如,要验证有效的 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");
}
Or, I've thought about using strcmp(str, str2) == 0, but this must be very complicated.
或者,我已经考虑过使用strcmp(str, str2) == 0,但这一定非常复杂。
Is there a standard C function that does such thing?
有没有标准的 C 函数可以做这样的事情?
回答by Aniket Inge
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
}
You also need #include<stdbool.h>or just replace boolwith int
您还需要#include<stdbool.h>或只是替换bool为int
回答by Rohan
I would suggest this:
我建议这样做:
char *checker = NULL;
checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
//you found the match
}
This would match only when string starts with 'http://'and not something like 'XXXhttp://'
这只会在字符串开头时匹配,'http://'而不是类似'XXXhttp://'
You can also use strcasestrif that is available on you platform.
strcasestr如果您的平台上可用,您也可以使用。
回答by tleb
A solution using an explicit loop:
使用显式循环的解决方案:
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
bool startsWith(const char *haystack, const char *needle) {
for (size_t i = 0; needle[i] != 'strstr(usUrl, "http://") == usUrl ;
'; i++) {
if (haystack[i] != needle[i]) {
return false;
}
}
return true;
}
int main() {
printf("%d\n", startsWith("foobar", "foo")); // 1, true
printf("%d\n", startsWith("foobar", "bar")); // 0, false
}
回答by Yasir Malik
strstr(str1, "http://www.stackoverflow")is another function that can be used for this purpose.
strstr(str1, "http://www.stackoverflow")是另一个可用于此目的的功能。
回答by Reno
The following should check if usUrl starts with "http://":
以下应检查 usUrl 是否以“http://”开头:
##代码##
