一、strcmp函数概述
strcmp函数(string compare)是一个高度常用的字符串比较函数,它定义在C标准库头文件中。该函数用于比较两个字符串是否相等,若相等则返回0,若s1>s2则返回一个正整数,若s1<s2则返回一个负整数。它比较字符串中每个字符的字节值(ASCII码值)大小,直到字符串中某一字符的字节值不等或某一字符串结束。该函数具有高效和可靠的特点,比较两个字符串时经常使用它。下面我们从几个方面详细介绍该函数的使用方法。
二、strcmp函数用法详解
1. strcmp函数的函数原型
int strcmp(const char *s1, const char *s2);
2. strcmp函数参数说明
s1和s2分别为待比较的两个字符串,函数的返回值为整数。
3. strcmp函数返回值说明
1. 若s1和s2相等,则返回0;
2. 若s1>s2,则返回一个正整数,其中这个正整数大小组合两个字符串中第一个不相同字符ASCII码的差值;
3. 若s1<s2, 则返回一个负整数,这个负整数大小组合两个字符串中第一个不相同字符ASCII码的差值。
4. strcmp函数示例
示例1(比较两个字符串是否相等)
#include <stdio.h> #include <string.h> int main(){ char str1[] = "hello world"; char str2[] = "hello world"; if (strcmp(str1, str2) == 0){ printf("str1和str2相等\n"); } else { printf("str1和str2不相等\n"); } return 0; }
示例2(比较两个字符串大小)
#include <stdio.h> #include <string.h> int main(){ char str1[] = "hello world"; char str2[] = "Hello world"; int result = strcmp(str1, str2); if (result > 0){ printf("str1比str2大\n"); } else if (result < 0){ printf("str1比str2小\n"); } else { printf("str1和str2相等\n"); } return 0; }
示例3(判断字符串是否与给定字符串开头相同)
#include <stdio.h> #include <string.h> int main(){ char str[] = "hello world"; if (strncmp(str, "hello", 5) == 0){ printf("str以hello开头\n"); } else { printf("str不以hello开头\n"); } return 0; }
三、总结
strcmp函数是C语言中非常常用的字符串比较函数之一,可以用于比较两个字符串是否相等,也可以用于比较两个字符串的大小。需要注意的是,在对函数的返回值进行判断时,要注意等于0的情况,因为函数在两个字符串相等时返回的是0,这一点在代码编写中要特别注意。
原创文章,作者:GSWFX,如若转载,请注明出处:https://www.506064.com/n/351746.html