3-4-3 字符串的比较

3.4.3 字符串的比较

1. 重载运算符(略)

  • >=

  • <=

  • ==

  • !=

2. Compare成员函数

compare成员函数提供比重载运算符更复杂、精密的比较手段:

  • 两个string

#include <cassert>
#include <string>
using namespace std;

int main()
{
string first("This");
string first("That");
assert(first.compare(second) > 0);

first.swap(second); //swap the two strings

assert(second.compare(first) < 0);
}
  • 两个string各自的子集

    • 参数:
      • s1起始下标
      • s1的字符数
      • s2
      • s2起始下标
      • s2的字符数
#include <cassert>
#include <string>
using namespace std;

int main()
{
string first("This is a day that will live in infamy");
string second("I don't believe that this is what I signed up for");

assert(first.compare(1, 7, second, 22, 7) == 0);
assert(first.compare(1, 9, second, 22, 9) < 0);
}

3. 取字符(at[])

  • at[]都取出字符,一般两者表现一致

  • 不同的地方在于数组越界时,at抛出一个out_of_range异常,而[]将会使程序中断