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()函数有两个参数str1和str2:
cstring库描述如下:
str1
1. C string to be compared.
str2
1. C string to be compared.
strcmp函数的返回值类型为int型:
cstring库描述如下:
1. Returns an integral value indicating the relationship between the strings:
示例代码如下所示:
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;
}
代码运行结果如下图所示:
编写自己的字符串拼接函数,示例代码如下所示:
int my_strcmp(const char* str1, const char* str2) {
//
assert(str1 != NULL);
assert(str2 != NULL);
//
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
//
return (unsigned char)*str1 - (unsigned char)*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;
}
代码运行结果如下图所示: