strcmp

函数简介

原型:extern int strcmp(const char *s1,const char * s2);
所在头文件:string.h
功能:比较字符串s1和s2。
一般形式:strcmp(字符串1,字符串2)
说明:
当s1<s2时,返回为负数 一般是-1
当s1=s2时,返回值= 0
当s1>s2时,返回正数 一般是1
即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。如:
"A"<"B" "a">"A" "computer">"compare"
特别注意:strcmp(const char *s1,const char * s2)这里面只能比较字符串,不能比较数字等其他形式的参数。

函数源码

1
2
3
4
5
6
7
8
9
10
11
int strcmp(const char *str1, const char *str2)
{
    while (*str1==*str2)
    {
        if(*str1=='\0')
            return 0;
        str1++;
        str2++;
     }
     return *str1-*str2;
}

 

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    char a[30]={'a','b','c','c','d','z'};
    char b[30]={'a','b','c','d','e'};
    char d[30]={'a','b','c','d','e'};
    char e[30]={'a','b','c','d','f'};
    int n=strcmp(a,b);
    int m=strcmp(b,d);
    int g=strcmp(a,b);
    int h=strcmp(e,b);
    cout<<n<<" "<<m<<" "<<g<<" "<<h<<endl;
    return 0;
    
}

 

#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
int main()
{
    char s1[10],s2[10];
    cin>>s1>>s2;
    int m=strcmp(s1,s2);
    cout<<m<<endl;
    return 0;
    
    
} 

输出的结果是-1  所以字符串比较并不取决于他的长度 

#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
int main()
{
    //char s1[10],s2[10];
    string s1,s2;
    cin>>s1>>s2;
    int m=strcmp(s1,s2);
    cout<<m<<endl;
    return 0;
    
    
} 

会出现错误

posted @ 2014-04-02 16:32  盒子先生★  阅读(252)  评论(0编辑  收藏  举报