字符串的赋值问题

来源:互联网 发布:动漫设计与制作软件 编辑:程序博客网 时间:2024/06/05 22:34
//判断字符串是否相等
char str1[] = "Hello World!";
char str2[] = "Hello World!";


char *str3 = "Hello World!";
char *str4 = "Hello World2!";




if (str1 == str2) //==只能比地址,(不能比较内容)
printf("str1 and str2 are same\n");
else
//两个字符串数组,分配两个长度相等的空间,将“Hello World!”复制进去,因此两个初始的地址不同
printf("str1 and str2 are not same\n"); 


if (strcmp(str1,str2))
printf("str1 and str2 are same\n");
else
printf("str1 and str2 are not same\n");


if (str3==str4)
   //两个指针指向相同的地址空间(同一块地址空间)存值为"Hello world!"
printf("指针:str3 and str4 are same\n");
else

printf("指针:str3 and str4 are not same\n");


if (!strcmp(str3, str4))
printf("str3 and str4 are same\n");
else
printf("str3 and str4 are not same\n");


//总结:==运算符比较的是两个字符串的地址。而strcmp函数比较的是两个字符串内容
 /*strcmp 函数说明:
   设这两个字符串为str1,str2,
   若str1 = str2,则返回零;
若str1<str2,则返回负数;
若str1>str2,则返回正数。*/
0 0