c++中的string用法(二)

转载自:http://www.programfan.com/blog/article.asp?id=16881

basic_string::compare

如果所比较的两个string相等,则返回0; 操作string 大于参数string,返回

正数;操作string小于参数string,返回负数。

(1)比较操作string_Str或C-string_Ptr

int compare( const basic_string&_Str) const;

int compare( const value_type*_Ptr) const;

int com =s.compare ( sp );

(2)比较操作string_Pos1(下标)开始的_Num1个字符 与 string_Str

比较操作string_Pos1(下标)开始的_Num1个字符 与 C-string_Ptr

比较操作stringPos1(下标)开始的Num1个字符 与StrOff(下标)开始Count个字

int compare( sizetype_Pos1, sizetypeNum1, const basicstring&_Str);

int compare( sizetype_Pos1, sizetypeNum1, const valuetype*_Ptr) const;

int compare( sizetype_Pos1, sizetypeNum1, const basicstring&_Str,

sizetype_Off, sizetype_Count);

int com1 =s.compare ( 2 , 3 , sp );

int com2 =s.compare ( 2 , 3 , c );

int com3 =s.compare ( 1 , 3 , cs , 3 ,1 );

basic_string::erase

删除string中的一个或几个元素。前两个成员函数,返回要被删除的子串的下

一个元素的iterator;第三个函数,返回删除后的string 的引用。

(1)删除string中从FirstLast的字符

iterator erase( iterator_First, iterator_Last);

basic_string ::iterator s_Iter;

s_Iter = s.erase ( s.begin ( ) + 3 , s.end ( ) - 1 );// s_Iter=s.end( )

(2)删除string_It所指的字符

iterator erase( iterator_It);

s_Iter = s.erase ( s.begin ( ) + 5 );

(3)删除string中从_Pos(下标)开始的_Count个字符

basicstring& erase( sizetypePos= 0, sizetype_Count=npos );

str = s.erase ( 6 , 8 );// str也是string

basic_string::find

寻找给定的string。返回找到的第一个string 下标值;如果没找到则返回npos。

(1)找一个character_Ch。(默认从头找)

sizetype find( valuetypeCh, sizetype_Off= 0 ) const;

string s ( "Hello Everyone" );

basic_string ::size_type index1, index2;

static const basic_string ::size_type npos = -1;

index1 = s.find ( "e" , 3 );// index1=8,不是6

index2 = s.find ( "x" );// index2=-1

if (indexCh1a != npos) cout <<indexCh1a << endl;

else cout << "The character 'e' was not found in str1 ." << endl;

(2)找一个C-string。(默认从头找)

sizetype find( const valuetype*Ptr, sizetype_Off= 0 ) const;

string s ( "Let me make this perfectly clear." );

basic_string ::size_type index;

const char *c = "perfect";

index = s.find ( c , 5 );// index=17

(3)找一个string。(默认从头找)

sizetype find( const basicstring&Str, sizetype_Off= 0 ) const;

string s ( "clearly this perfectly unclear." );

basic_string ::size_type index;

string sta ( "clear" );

index = s.find ( sta , 5 );// index=24

原文链接: https://www.cnblogs.com/allenzhaox/archive/2013/01/07/3201755.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74736

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午4:33
下一篇 2023年2月9日 下午4:33

相关推荐