MemoryGarden's Blog

努力 -----------大能猫

C++博客 首页 新随笔 联系 聚合 管理
  118 Posts :: 11 Stories :: 20 Comments :: 0 Trackbacks
1 int compare ( const string& str ) const;
2 int compare ( const char* s ) const;
3 int compare ( size_t pos1, size_t n1, const string& str ) const;
4 int compare ( size_t pos1, size_t n1, const char* s) const;
5 int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 ) const;
6 int compare ( size_t pos1, size_t n1, const char* s, size_t n2) const;



Compares the content of this object (or a substring of it, known as compared (sub)string) to the content of a comparing string, which is formed according to the arguments passed.
The member function returns 0 if all the characters in the compared contents compare equal, a negative value if the first character that does not match compares to less in the object than in the comparing string, and a positive value in the opposite case.
Notice that for string objects, the result of a character comparison depends only on its character code (i.e., its ASCII code), so the result has some limited alphabetical or numerical ordering meaning.
For other basic_string class instantitations, the comparison depends on the specific traits::compare function, where traits is one of the class template parameters.


0
if the compared characters sequences are equal, otherwise a number different from 0 is returned, with its sign indicating whether the object is considered greater than the comparing string passed as parameter (positive sign), or smaller (negative sign).

 1 // comparing apples with apples
 2 #include <iostream>
 3 #include <string>
 4 using namespace std;
 5 
 6 int main ()
 7 {
 8   string str1 ("green apple");
 9   string str2 ("red apple");
10 
11   if (str1.compare(str2) != 0)
12     cout << str1 << " is not " << str2 << "\n";
13 
14   if (str1.compare(6,5,"apple"== 0)
15     cout << "still, " << str1 << " is an apple\n";
16 
17   if (str2.compare(str2.size()-5,5,"apple"== 0)
18     cout << "and " << str2 << " is also an apple\n";
19 
20   if (str1.compare(6,5,str2,4,5== 0)
21     cout << "therefore, both are apples\n";
22 
23   return 0;
24 }






posted on 2009-12-30 02:11 memorygarden 阅读(890) 评论(0)  编辑 收藏 引用 所属分类: STL

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理