C++ string class

来源:互联网 发布:光通讯网络交换机 编辑:程序博客网 时间:2024/06/18 18:23
string::compare

   C++字符串支持常见的比较操作符(>,>=,<,<=,==,!=),甚至支持stringC-string的比较(str<</span>”test”)。在使用>,>=,<,<=这些操作符的时候是根据“当前字符特性”将字符按字典顺序进行逐一得比较。字典排序靠前的字符小,比较的顺序是从前向后比较,遇到不相等的字符就按这个位置上的两个字符的比较结果确定两个字符串的大小。同时,string(“abcd”) 另一个功能强大的比较函数是成员函数compare()。他支持多参数处理,支持用索引值和长度定位子串来进行比较。他返回一个整数来表示比较结果,返回值意义如下:0--相等,>0--大于  ,<0--小于。举例如下:

  string s(abcd);

  s.compare(abcd);//返回0

  s.compare(dcba);//返回一个小于0的值

  s.compare(ab);//返回大于0的值

 补充:

1int compare(const basic_string& str) constnoexcept;
    Effects:Determines the effective length rlen of the strings to compare asthe smallest of size()and str.size(). The function then comparesthe two strings by callingtraits::compare(data(),str.data(),rlen).

对于traits::compare(data(),str.data(),rlen)

typedef char char_type;
static int compare(const char_type* s1, const char_type* s2, size_tn);

--------------------------------------------------

2int compare(const basic_string&str) const noexcept;

s.compare(s); //相等

--------------------------------------------------

3intcompare(size_typepos1, size_type n1,const basic_string&str,size_type pos2, size_type n2 ) const;

Returns:basic_string(*this, pos1,n1).compare(basic_string(str, pos2, n2)).

4 int compare(size_type pos1, size_type n1,constbasic_string& str) const;

Returns:basic_string(*this,pos1,n1).compare(str).

  s.compare(0,2,s,2,2);//用”ab”和”cd”进行比较 小于零

s.compare(0,2,s);//用”ab”和”abcd”进行比较

比较34这两个函数,seeking猜测:pos2n2是带有默认值0的参数

补充说明:typedef unsinged  basic_string::size_type 

--------------------------------------------------

5intcompare(size_type pos, size_type n1,const charT *s, size_type n2)const;

  Returns:basic_string(*this, pos1,n1).compare(basic_string(str, pos2, n2))

6intcompare(size_type pos, size_type n1,const charT *s)const;

  Returns:basic_string(*this, pos,n1).compare(basic_string(s))

s.compare(1,2,bcx,2); //用”bc”和”bc”比较。

s.compare(1,2,bcx);//用”bc”和”bcx”比较。

  比较56这两个函数,seeking:n2是一个带有默认值0的参数

补充说明:charT是模板参数,表示变量的数据类型。关于charT参见string class的定义。

--------------------------------------------------
原创粉丝点击