c++ str比较

 传统的c字符串比较必须用strcmp函数:(不能用==,否则比较的只是两个地址)

函数名: strcmp
功  能: 串比较
用  法: int strcmp(char *str1, char *str2);
看Asic码,str1>str2,返回值 > 0;两串相等,返回0

上面的头文件为<string.h> strncasecmp()是忽略大小写的。


c++ string 类型的比较可以用string的函数compare()
int compare ( const string& str ) const;
int compare ( const char* s ) const;

或直接用==比较

复制代码
 //  比较两个字符串   比较规则同 c字符串比较规则
    string str7, str8;
    cout << "输入字符串 str7, str8 , 中间用空格格开" << endl;
    cin >> str7 >> str8;

    if( str7< str8 ) cout << str7 << "  小于 " << str8 << endl;
    else if( str7> str8 ) cout << str7 << "  大于 " << str8 << endl;
    else cout << str7 << "  等于 " << str8 << endl;
复制代码

 

可以直接把string类型和c字符串类型比较:

 string s("abc");
  s=="abc" //true,此时C风格字符串可以转换为string类型的

猜你喜欢

转载自blog.csdn.net/qq_32511517/article/details/80768097