Home > Article > Backend Development > What is the string comparison function in C language
#The string comparison function in C language is the strcmp() function.
Let’s introduce this function in detail.
Function prototype:
int strcmp(const char *s1, const char *s2);
Header file:
#include <string.h>
Function: Used to compare two strings.
Parameters: s1 and s2 are two strings to be compared.
Return value: If the strings s1 and s2 are equal, zero is returned; if s1 is greater than s2, a number greater than zero is returned; otherwise, a number less than zero is returned.
Explanation: The strcmp() function compares two strings based on the value of the ACSII code; the strcmp() function first subtracts the first character of s2 from the first character value of the s1 string. If If the difference is zero, the comparison continues; if the difference is not zero, the difference is returned. Until a different character appears or '\0' is encountered.
Note: strcmp(const char * s1, const char * s2) can only compare strings, not numbers and other parameters.
Code example:
#include <string.h> int main(void){ char *p="aBc"; char *q="Abc"; char *h="abc"; printf("strcmp(p,q):%d\n",strcmp(p,q)); printf("strcmp(p,h):%d\n",strcmp(p,h)); return 0; } //结果: //strcmp(p,q):32 //strcmp(p,h):-32
Recommended tutorial: C language tutorial
The above is the detailed content of What is the string comparison function in C language. For more information, please follow other related articles on the PHP Chinese website!