La funzione strcmp () confronta due stringhe e restituisce 0 se entrambe le stringhe sono identiche.
Prototipo C strcmp ()
int strcmp (const char * str1, const char * str2);
La strcmp()
funzione accetta due stringhe e restituisce un numero intero.
Il strcmp()
confronto carattere due stringhe per carattere.
Se il primo carattere di due stringhe è uguale, viene confrontato il carattere successivo di due stringhe. Questo continua fino a quando i caratteri corrispondenti di due stringhe sono diversi o ' '
viene raggiunto un carattere nullo .
È definito nel string.h
file di intestazione.
Valore restituito da strcmp ()
Valore di ritorno | Osservazioni |
---|---|
0 | se entrambe le stringhe sono identiche (uguali) |
negativo | se il valore ASCII del primo carattere senza corrispondenza è inferiore al secondo. |
intero positivo | se il valore ASCII del primo carattere non corrispondente è maggiore del secondo. |
Esempio: funzione C strcmp ()
#include #include int main() ( char str1() = "abcd", str2() = "abCd", str3() = "abcd"; int result; // comparing strings str1 and str2 result = strcmp(str1, str2); printf("strcmp(str1, str2) = %d", result); // comparing strings str1 and str3 result = strcmp(str1, str3); printf("strcmp(str1, str3) = %d", result); return 0; )
Produzione
strcmp (str1, str2) = 32 strcmp (str1, str3) = 0
Il primo carattere senza corrispondenza tra le stringhe str1 e str2 è il terzo carattere. Il valore ASCII di "c" è 99 e il valore ASCII di "C" è 67. Pertanto, quando vengono confrontate le stringhe str1 e str2, il valore restituito è 32.
Quando vengono confrontate le stringhe str1 e str3, il risultato è 0 perché entrambe le stringhe sono identiche.