2013-03-20 10 views
5

Ad esempio, per convalidare la validità URL, mi piacerebbe fare quanto segueCome verificare se la stringa inizia con una determinata stringa in 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"); 
} 

Oppure, ho pensato di usare strcmp(str, str2) == 0, ma questo deve essere molto complicato.

Esiste una funzione C standard che esegue tale operazione?

+2

Si prega di provare 'strncmp'. – congusbongus

+0

possibile duplicato di [Qualcosa come \ "startsWith (str \ _a, str \ _b) \' in C?] (Http://stackoverflow.com/questions/4770985/qualcosa-come -startici constr-a-str-b- in-c) –

risposta

0

strstr(str1, "http://www.stackoverflow") è un'altra funzione che può essere utilizzata per questo scopo.

6

vorrei suggerire questo:

char *checker = NULL; 

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

} 

Questo sarebbe partita solo quando stringa inizia con 'http://' e non qualcosa di simile 'XXXhttp://'

si può anche usare strcasestr se questo è disponibile su di voi piattaforma.

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 
} 

È inoltre necessario #include<stdbool.h> o semplicemente sostituire bool con int

+0

Così tante risposte errate per questa domanda. Questo è quello che funziona correttamente. – PoVa

0

Il seguente dovrebbe controllare se usUrl inizia con "http: //":

strstr(usUrl, "http://") == usUrl ; 
Problemi correlati