strcmp()是 C 语言中的一个标准库函数,用于比较两个字符串。它逐个字符地比较字符串中的字符,直到发现差异或者比较到字符串的结束符'\0'。
strcmp 函数头文件
strcmp函数的头文件是<string.h>。在使用strcmp函数前,确保在你的 C 代码中包含这个头文件:
#include <string.h>
strcmp 函数原型
int strcmp(const char *s1, const char *s2);
strcmp函数将s1指向的字符串与s2指向的字符串逐字符进行比较,发现差异或终止符'\0'时返回;
参数说明
s1:指向第一个字符串的指针;s2:指向第二个字符串的指针;
返回值
strcmp函数返回大于、等于或小于0的整数;
strcmp()函数会逐字符地比较两个字符串的 ASCII 值,当字符不同时,它会返回两个字符差的值;如果字符串完全相同,返回0。
strcmp 示例代码
比较两个字符串是否相同
#include <stdio.h>
#include <string.h>
int main() {
    
    char str1[] = "hello";
    char str2[] = "world";
    if (strcmp(str1,str2) == 0) {
        printf("The two strings are identical.\n");
    } else {
        printf("The two strings are different.\n");
    }
    
    return 0;
}