1 函数原型
strcmp():比较两个字符串大小,函数原型如下:
int strcmp ( const char * str1, const char * str2 );
cstring库描述如下:
Compare two strings
1. Compares the C string str1 to the C string str2.
2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
3. This function performs a binary comparison of the characters.
- strcmp()函数:
(1)比较字符串str1和字符串str2的大小; - 比较过程
(1)二进制比较:比较是基于字符的 ASCII 值进行的;
(2)逐字符比较:首先比较字符串str1和字符串str2的第一个字符。
(3)相等检查:如果相等,则继续比较下一个字符对;
(4)终止条件:该过程持续进行,直至两个字符串有一对字符不相等或其中一个字符串到达其末尾的空字符’\0’。
2 参数
strcmp()函数有两个参数str1和str2:
- 参数str1是指向第一个待比较的字符串的指针,类型为char*型;
- 参数str2是指向第二个待比较的字符串的指针,类型为char*型。
cstring库描述如下:
str1
1. C string to be compared.
str2
1. C string to be compared.
3 返回值
strcmp函数的返回值类型为int型:
- 如果str1大于str2,返回值大于0;
- 如果str1等于str2,返回值等于0;
- 如果str1小于str2,返回值小于0。
cstring库描述如下:
1. Returns an integral value indicating the relationship between the strings:
4 示例
4.1 示例1
示例代码如下所示:
int main()
{
//
char str1[] = "Hello world";
char str2[] = "hello world";
char str3[] = "Hello";
char str4[] = { 72,101,108,108,111,32,119,111,114,108,100,0 };
//
if (strcmp(str1, str2) > 0) {
printf("字符串\"%s\" > 字符串\"%s\"\n", str1, str2);
}
else if (strcmp(str1, str2) == 0) {
printf("字符串\"%s\" = 字符串\"%s\"\n", str1, str2);
}
else {
printf("字符串\"%s\" < 字符串\"%s\"\n", str1, str2);
}
//
if (strcmp(str1, str3) > 0) {
printf("字符串\"%s\" > 字符串\"%s\"\n", str1, str3);
}
else if (strcmp(str1, str3) == 0) {
printf("字符串\"%s\" = 字符串\"%s\"\n", str1, str3);
}
else {
printf("字符串\"%s\" < 字符串\"%s\"\n", str1, str3);
}
//
if (strcmp(str1, str4) > 0) {
printf("字符串\"%s\" > 字符串\"%s\"\n", str1, str4);
}
else if (strcmp(str1, str4) == 0) {
printf("字符串\"%s\" = 字符串\"%s\"\n", str1, str4);
}
else {
printf("字符串\"%s\" < 字符串\"%s\"\n", str1, str4);
}
//
return 0;
}
代码运行结果如下图所示:
4.2 示例2
编写自己的字符串拼接函数,示例代码如下所示:
int my_strcmp(const char* str1, const char* str2) {
//
assert(str1 != NULL);
assert(str2 != NULL);
//
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
//
return (*str1 - *str2);
}
int main()
{
//
char str1[] = "Hello world";
char str2[] = "hello world";
char str3[] = "Hello";
char str4[] = { 72,101,108,108,111,32,119,111,114,108,100,0 };
//
if (my_strcmp(str1, str2) > 0) {
printf("字符串\"%s\" > 字符串\"%s\"\n", str1, str2);
}
else if (my_strcmp(str1, str2) == 0) {
printf("字符串\"%s\" = 字符串\"%s\"\n", str1, str2);
}
else {
printf("字符串\"%s\" < 字符串\"%s\"\n", str1, str2);
}
//
if (my_strcmp(str1, str3) > 0) {
printf("字符串\"%s\" > 字符串\"%s\"\n", str1, str3);
}
else if (my_strcmp(str1, str3) == 0) {
printf("字符串\"%s\" = 字符串\"%s\"\n", str1, str3);
}
else {
printf("字符串\"%s\" < 字符串\"%s\"\n", str1, str3);
}
//
if (my_strcmp(str1, str4) > 0) {
printf("字符串\"%s\" > 字符串\"%s\"\n", str1, str4);
}
else if (my_strcmp(str1, str4) == 0) {
printf("字符串\"%s\" = 字符串\"%s\"\n", str1, str4);
}
else {
printf("字符串\"%s\" < 字符串\"%s\"\n", str1, str4);
}
//
return 0;
}
代码运行结果如下图所示: