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);
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章