一、compare
昨天刷Leetcode的的时候发现string.compare(str)的用法,第一次看见这个,不太了解,今天总结一下子。我们写出下列的测试代码:
#include<iostream>
#include<string>
using namespace std;
int main(){
//string.compare 一样则返回0
string a = "abcdefg";
string b = "bcde";
int i = a.compare(b);//a与b完整对比
int j = a.compare(1,4,b);//“bcde”与b对比
int k = a.compare(1,3, b,0,3);//"bcd"与bcd对比
cout << i << " " << j << " " << k << " " << endl;
return 0;
}
结果如下图所示:
扩展多一点情况,写出以下代码:
#include<iostream>
#include<string>
using namespace std;
int main(){
string a = "abcdefg";
string b = "bcde";
int i = a.compare(b);
int j = a.compare(1,4,b);
int k = a.compare(1,3, b,0,3);
cout << i << " " << j << " " << k << " " << endl;
int ii = a.compare(3,2,b);//"de" "bcde"
int jj = a.compare(1,2,b);//"bc" "bcde"
int kk = a.compare(1,3,b,0,2);//"bcd" "bc"
cout << ii << " " << jj << " " << kk << endl;
return 0;
}
~
结果如下图所示:
没有发现什么规律,得出结论:运用string.compare(b),当sting与b完全相同时,返回0,可以引用两个int值截断string与b做比较。