http://blog.sina.com.cn/s/blog_957f79a801011efr.html(2012-04-05 20:34:55)
#include <string.h>
char s1[10],s2[10];
...
if(strcmp(s1,s2)==0)
printf("两字符串相等\n");
string.h 头文件中就有比较函数,可以用来比较是否相等
2:这个是普通方法 不调用函数strcmp();
#include <stdio.h>
int comparision(char a[],char b[])
{
int t,i=0;
while(a[i]!='\0'||b[i]!='\0')
{
if(a[i]==b[i]) t=0;
else if(a[i]>b[i]) t=1;
else t=-1;
if(t!=0) break;
i++;
}
return t;
}
main(void)
{
char a[40],b[40];
int k=0;
gets(a);
gets(b);
k=comparision(a,b);
if(k==1) printf("a[40]>b[40]");
else if(k==-1) printf("a[40]<b[40]");
else printf("a[40]=b[40]");
}
【解惑】C语言中为什么两个字符串不能直接进行比较?
大家都知道,在C语言中两上字符串是不能直接进行比较的,我们一般使用<string.h>中的字符串比较函数strcmp()来进行两个字符串的比较。那么,为什么不允许两个字符串直接进行比较呢?可做如下解释:
有如下代码:
char s1[] = "abc";
char s2[] = "abc";
如果直接进行比较:
if (s1 == s2)
{
printf("s1等于 s2");
}
else
{
printf("s1 不等于s2");
}
大家想想输出结果会是什么呢?
输出结果永远为:s1 不等于 s2.(不论你换成char s1[] = "abc"; char s2[] = "def";
还是char s1[] = "def"; char s2[] = "abc";,输出结果都一样)。
为什么呢?
大家因为这样比较,其实是在把s1和s2当作指针来进行比较,而不是比较两个数组中的内容。因为s1和s2在内存中位置肯定不同,所以s1
== s2的值肯定为0,所以出现上面的结果也就是理所当然了。
这个应该可以追溯到C语言中 数组(字符串也可认为是数组)的访问机制
|
|