C++中string类型与char*类型的字符串比较的一种实例
在c语言中一般通过strcmp函数来比较两个字符串。
strcmp容易有缓冲区溢出错误,比如对于代码strcmp(p,"abc"),若p指向一个未知内存块,则“abc”会一直比较下去,直到错误。
可以用strncmp代替。不过有点想太多了。
使用strcmp比较,需先将string转换成char*类型再比较。可以用c_str()函数转换。
网上搜索了很多方法都是用strcmp,这里我想用string类自身的比较函数compare来比较字符串。
compare其中的一个重载:int compare (const char* s) const;
下面是例程。一个字符一个字符码的,无编译错误。
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 int main(void) 6 { 7 const char *passwd = "ap_passwd"; 8 string str = "ap_passwd"; 9 10 cout<<"passwd="<<passwd<<", str="<<str<<endl; 11 12 if ( str.compare(passwd) == 0) 13 { 14 cout<<"The compare euqal!"<<endl; 15 } 16 else 17 { 18 cout<<"is not equal!"<<endl; 19 } 20 21 return 0; 22 }
编译:@sw:~$g++ test.cpp
运行:@sw:~$ ./a.out
passwd=ap_passwd, str=ap_passwd
The compare euqal!
附compare详细用法:http://www.cplusplus.com/reference/string/string/compare/
浙公网安备 33010602011771号