如何检查字符串是否以C中的某个字符串开头?
例如,要验证有效的Url,我想执行以下操作如何检查字符串是否以C中的某个字符串开头?,c,string,C,String,例如,要验证有效的Url,我想执行以下操作 char usUrl[MAX] = "http://www.stackoverflow" if(usUrl[0] == 'h' && usUrl[1] == 't' && usUrl[2] == 't' && usUrl[3] == 'p' && usUrl[4] == ':' && usUrl[5] == '/' &&
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");
}
或者,我考虑过使用strcmp(str,str2)==0,但这一定非常复杂
有没有一个标准的C函数可以做这样的事情http://www.stackoverflow“”是可用于此目的的另一个功能。我建议:
char *checker = NULL;
checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
//you found the match
}
只有当字符串以'http://'
开头,而不是类似于'XXXhttp://'
如果平台上有可用的话,您也可以使用strcasestr
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
}
您还需要
#包括
或将bool
替换为int
以下内容应检查usUrl是否以“http://”开头:
使用显式循环的解决方案:
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
bool startsWith(const char *haystack, const char *needle) {
for (size_t i = 0; needle[i] != '\0'; 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
}
#包括
#包括
#包括
bool startsWith(常量字符*干草堆,常量字符*针){
用于(尺寸i=0;针[i]!='\0';i++){
if(haystack[i]!=针[i]){
返回false;
}
}
返回true;
}
int main(){
printf(“%d\n”,startsWith(“foobar”,“foo”);//1,true
printf(“%d\n”,startsWith(“foobar”,“bar”);//0,false
}
请尝试strncmp
。这个问题可能重复了这么多不正确的答案。这是一个正常工作的。或return!strncmp(a,b,strlen(b))
这将一直检查到usUrl的末尾,即使开头不匹配,这可能会有非常糟糕的性能。strstrstr
查找字符串中第一个出现的子字符串。有人可以做“你好http://www.stackoverflow“
和strstr
仍将返回指针(基本上是查找事件)。我看到这是另一个功能,但仍然没有回答用户的问题。
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
bool startsWith(const char *haystack, const char *needle) {
for (size_t i = 0; needle[i] != '\0'; 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
}