2013-03-20 9 views
5

たとえば、有効なURLを検証するために、私は次のよう文字列がCで特定の文字列で始まるかどうかを確認する方法は?

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関数はありますか?

+2

'strncmp'を試してみてください。 – congusbongus

+0

の可能な複製[startWith(str \ _a、str \ _b)\ 'Cのような何か?](http://stackoverflow.com/questions/4770985/something-like-startswithstr-a-str-b- in-c) –

答えて

0

strstr(str1, "http://www.stackoverflow")は、この目的に使用できる別の機能です。

6

私はこのことをお勧め:これは、文字列は'XXXhttp://'

のようなものを'http://'から始まり、いない場合にのみ、それはあなたのプラットフォーム上で利用可能である場合にもstrcasestrを使用することができます一致します

char *checker = NULL; 

checker = strstr(usUrl, "http://"); 
if(checker == usUrl) 
{ 
    //you found the match 

} 

を。

25
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>必要とするか、または単にusUrlは "のhttp://":で始まるかどうかを確認する必要があり、次のint

+0

この質問には多くの誤った回答があります。これは正しく動作するものです。 – PoVa

0

boolを置き換える

strstr(usUrl, "http://") == usUrl ; 
関連する問題