导论
在判断两个字符串的内容是否相等的时候,如果使用==
,当两个字符串不是指向内存中同一地址时,那么即使这两个字符串内容一样,但是用==
比较出来的结果也是 false。所以两个字符串在比较内容是否相等的时候一定要使用strcmp()
。
正文
strcmp()函数
为了便于大家的阅读和理解,在这里先简单的介绍下strcmp()
函数
使用格式:
#include<string.h>
int strcmp(const char* s1,const char* s2);
当s1<s2时,返回为负数;
当s1==s2时,返回值= 0;
当s1>s2时,返回正数。
即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。如:
"A"<"C"
、"d">"D"
、 "computer">"compare"
注意:
strcmp(const char *s1,const char * s2)
只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。- 不同编译器下,
strcmp()
函数返回的具体数值不同。
实例
1.字符串比较
#include<stdio.h>
int main()
{
char ch1 = "hello";
char ch2 = "hello";
printf("%d\n", ch1 == ch2);
}
输出结果为1:说明字符串常量可以直接用==
比较,若相等则返回1。
2.字符串变量比较
#include<stdio.h>
#include<string.h>
char *arr1 = "hello";
char arr2[] = "hello";
if (arr1 == "hello")
printf("1\n");
if (arr2 == "hello")
printf("2\n");
if (strcmp(arr1, "hello"))
printf("3\n");
if (strcmp(arr2, "hello"))
printf("4\n");
//输出结果是 1
为了更好的解释上述结果,我们更改一下代码:
int main()
{
char *arr1 = "hello";
char arr2[] = "hello"; //输出结果:
printf("%d\n",arr1 == "hello"); //1
printf("%d\n",arr2 == "hello"); //0
//strcmp函数,判断相等则返回0
printf("%d\n",strcmp(arr1,"hello")); //0
printf("%d\n",strcmp(arr2,"hello")); //0
}
说明:
-
arr2 == "hello"
是不成立的。字符串的比较不能用==
-
strcmp(arr1,"hello")
,strcmp(arr2,"hello")
都是成立的.
原因:
- 由于
"hello"
是字符串常量,编译器会进行优化:
所有的"hello"
都是相同的,整个程序中只需要有一个"hello"
字符串。然后所有引用"hello"
这个字符串的“指针变量”都赋值成相同的地址。所以:char *arr1 = "hello";
定义后,arr1
和"hello"
的地址是相同的。 - 对于:
char arr2[] = "hello";
,这里arr2并不是指针,类型里已经说明它是一个数组,所以这会是另一个内存地址,arr2与"hello"
的地址是不同的。
3.字符串数组比较
int main()
{
char arr1[] = "hello";
char arr2[] = "hello"; //输出结果:
printf("%d\n",arr1 == "hello"); //0
printf("%d\n",arr2 == "hello"); //0
printf("%d\n",arr1 == arr2); //0
//strcmp函数,判断相等则返回0
printf("%d\n",strcmp(arr1,arr2)); //0
}
解释:
我们已经知道了,前两条语句输出结果为0的原因是因为==
判断两边的地址不同,所以结果为0,同理,arr1和arr2在内存中存储的地址也不同,==
在判断时,发现两边的地址不同,输出结果为0。
结论
- 如果是比较两个字符,则可以用
==
直接进行比较 - 字符串常量可以直接用
==
比较,若相等则返回1。 - 在比较两个字符串变量时不能利用符号
==
,==
符号比较的是两个字符串的地址是否相等 - 比较
==
字符串数组的话,一定是不等的,因为他们的地址不同,此时就需要strcmp()
函数进行比较