您的位置:首页 > 编程语言 > C语言/C++

C++中string类型与char*类型的字符串比较剖析

2013-07-31 16:15 441 查看
C++中的string字符串可以直接进行比较,事实上strcmp()的两个参数是char*类型的,也就是说是比较C字符串的(即char数组),于是就不能用于比较string类型了

int strcmp( const char *string1, const char *string2 );

Value    Relationship of string1 to string2 
< 0       string1 less than string2 
 0        string1 identical to string2 
> 0       string1 greater than string2


但是string对象通过string类的方法 c_str() 就是可以进行比较的了

string类型的直接比较 strcmp比较char*字符串或者是通过c_str()转换来的char*字符串 都是比较ASCII码

如果直接比较char*字符串的话就会发现 是在比较内存中的位置,在前者较大

#include <iostream>
#include<cstring>
using namespace std;

int main()
{
    string s  = "abc";
    string s1 = "abd";

    if(s<s1)
    cout<<"string 类型 s = abc s1 = abd 直接比较   s小于s1"<<endl<<endl;

    if(strcmp(s.c_str(),s1.c_str())<0)
     cout<<"string 类型 s = abc s1 = abd 用c_str()转换成char*后strcmp比较 s小于s1"<<endl<<endl;

    cout<<"char* 数组比较"<<endl<<endl;

    char s2[10] = "abc";
    char s3[10] = "def";
    if(strcmp(s2,s3)<0)
    cout<<"strcmp比较  s2小于s3"<<endl<<endl;

    if(s2>s3)
    cout<<"直接比较s2大于s3,明显是按照地址先后进行比较的";
    return 0;
}


以上是例程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: