string compare

简介

就是 string对于string的比较函数

参考链接

http://www.cplusplus.com/reference/string/string/compare/

code

void NORMAL::testStringCompare() {
    string s1 = "123456789";
    string s2 = "213456789";
    string s3 = "123456789";
    string s4 = "123";
    cout << s1.compare(s2) << endl;
    cout << s2.compare(s1) << endl;
    cout << s1.compare(s4) << endl;
    cout << s4.compare(s1) << endl;
    cout << s1.compare(s3) << endl;
}

运行结果

-1
1
6
-6
0

归纳总结

相等 返回 0
不相等, 返回第一个字符表示的数的差值.
不相等的另一种情况, 前面相等, 但是短了, 返回长/短的字符数量.

代码验证

      /**
       *  @brief  Compare to a string. // 比较另一个字符串
       *  @param __str  String to compare against. // 要去比较的字符串
       *  @return  Integer < 0, 0, or > 0. // 返回参数 整数小于0 等于0 或者大于0
       *
       *  Returns an integer < 0 if this string is ordered before @a
       *  __str,  // 返回 整数 小于 0, 说明这个字符串的字符序列(ascii码)在参数字符串前面
        0 if their values are equivalent, // 0 说明相等
        or > 0 if this
       *  string is ordered after @a __str.  Determines the effective // 说明自己的字符串比参数字符串后面
       *  length rlen of the strings to compare as the smallest of
       *  size() and str.size().  The function then compares the two
       *  strings by calling traits::compare(data(), str.data(),rlen).
       *  If the result of the comparison is nonzero returns it,
       *  otherwise the shorter one is ordered first.
      */
      int
      compare(const basic_string& __str) const
      {
	const size_type __size = this->size();
	const size_type __osize = __str.size();
	const size_type __len = std::min(__size, __osize);

	int __r = traits_type::compare(_M_data(), __str.data(), __len); // 没找到源码 猜测应该是比较一定长的数据, 如果他们在一定长度内都相等, 会返回0, 然后程序
                                                                        // 会继续检查他们的长度, 和我猜测的长度差是一样的.
	if (!__r)
	  __r = _S_compare(__size, __osize); // 自己字符串的长度  和  参数字符串的长度比较
	return __r;
      }
      static int
      _S_compare(size_type __n1, size_type __n2) _GLIBCXX_NOEXCEPT // 这里就做了一个是否超过int最大的范围了么? 可能一个超级超级长的字符串的比较. 和我猜测的一样.
      {
	const difference_type __d = difference_type(__n1 - __n2);

	if (__d > __gnu_cxx::__numeric_traits<int>::__max)
	  return __gnu_cxx::__numeric_traits<int>::__max;
	else if (__d < __gnu_cxx::__numeric_traits<int>::__min)
	  return __gnu_cxx::__numeric_traits<int>::__min;
	else
	  return int(__d);
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章