#include < iostream >
#include < string>
#include < cctype>
using std::cout;
using std::endl;
using std::cin;
using std::string;
int main(void){
string str1=“hi,test,hello”;
string str2=“hi,test”;
//字符串比较
if(str1.compare(str2)>0)
printf(“str1>str2\n”);
else if(str1.compare(str2)<0)
printf(“str1<str2\n”);
else
printf(“str1==str2\n”);
//str1的子串(从索引3开始,包含4个字符)与str2进行比较
if(str1.compare(3,4,str2)==0)
printf("str1的指定子串等于str2\n");
else
printf("str1的指定子串不等于str2\n");
//str1指定子串与str2的指定子串进行比较
if(str1.compare(3,4,str2,3,4)==0)
printf("str1的指定子串等于str2的指定子串\n");
else
printf("str1的指定子串不等于str2的指定子串\n");
//str1指定子串与字符串的前n个字符进行比较
if(str1.compare(0,2,"hi,hello",2)==0)
printf("str1的指定子串等于指定字符串的前2个字符组成的子串\n");
else
printf("str1的指定子串不等于指定字符串的前2个字符组成的子串\n");
return 0;
}
场景
1.std::string 我们经常用来存储字符串数据, 当然它也可以作为byte的存储器,存储任意字节.
2.通常情况下我们使用 std::string 的 compare 方法比较字符串, 但这个方法比较奥字符串是不可靠的.
说明
1.compare 方法和 strcmp并不相同, 它比较的是 std::string size()大小里的所有字节.在size() 长度范围里, 如果有’\0’字符, 一样进行比较, 所有在不知道 std::string里是否存储纯字符串时, 最好先转换为 const char* (调用c_str()) , 再调用 strcmp比较. 这个坑还是很吓人的.
例子
1.以下例子很好的说明在比较字符串时 compare并不适合.
#include < iostream>
#include < string.h>
int main(int argc, char const *argv[]){
std::string str(“hello”);
str.append(1,’\0’);
str.append(1,‘i’);
std::cout << str.size() << std::endl;
std::cout << str << std::endl;
std::cout << str.compare(“hello”) << std::endl;
std::cout << strcmp(str.c_str(),“hello”) << std::endl;
return 0;
}
输出:
$ ./test-string.exe
7
hello
2
0
本文深入探讨了在C++中使用std::string的compare方法进行字符串比较时可能遇到的问题,特别是当字符串中包含null终止符时的行为差异。通过具体代码示例,揭示了compare与传统strcmp函数在处理此类情况下的不同之处,强调了在不确定字符串内容时应如何正确转换和比较。

1万+

被折叠的 条评论
为什么被折叠?



