[英]How to check if string starts with certain string in C?
例如,要驗證有效的 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");
}
或者,我已經考慮過使用strcmp(str, str2) == 0
,但這一定非常復雜。
有沒有標准的 C 函數可以做這樣的事情?
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
}
你還需要#include<stdbool.h>
或者只是用int
替換bool
我建議這樣做:
char *checker = NULL;
checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
//you found the match
}
僅當字符串以'http://'
而不是'XXXhttp://'
如果您的平台上可用,您也可以使用strcasestr
。
使用顯式循環的解決方案:
#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
}
以下應檢查 usUrl 是否以“http://”開頭:
strstr(usUrl, "http://") == usUrl ;
strstr(str1, "http://www.stackoverflow")
是另一個可用於此目的的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.