|
标签:杂谈 |
我的博友们,抱歉这么久时间没更新博客,是因为我一直都在Q-Zone上做更新,因为方便,所以如果大家还有想交我这个朋友的,请到以下链接 谢谢,也可以加我为好友。
之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。我们可以用
= 进行赋值操作,== 进行比较,+ 做串联(是不是很简单?)。我们尽可以把它看成是C++的基本数据类型。
首先,为了在我们的程序中使用string类型,我们必须包含头文件 。如下:
1.声明一个C++字符串
声明一个字符串变量很简单:
这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str初始化为一个空字符串。String类的构造函数和析构函数如下:
a)
b)
c)
basic_string::max_size
返回string 能放的最大元素个数。(不同于capacity)
size _ type max _ size( ) const;
basic_string <char>::size_type cap, max;
cap = s.capacity ( );
max = s.max_size ( ); // max=4294967294.
basic_string::rfind
寻找给定的string。返回找到的第一个string 下标值;如果没找到则返回npos。
与find 不同的是:rfind 默认从npos 开始找。其他相同。
basic_string::replace
将原string 中的元素或子串替换。返回替换后的string。
(1)用string 或C-string 代替操作string 中从 _Pos1 开始的 _Num1 个字符
basic _ string& replace( size _ type _Pos1 ,size _ type _Num1 ,
const value _ type* _Ptr );
basic _ string& replace(size _ type _Pos1 ,size _ type _Num1
,const basic _ string _Str );
string a,b;
string s ( 'AAAAAAAA' );
string s1p ( 'BBB' );
const char* cs1p = 'CCC' ;
a = s.replace ( 1 , 3 , s1p ); // s= ” ABBBAAAA ”
b = s.replace ( 5 , 3 , cs1p ); // s= ” ABBBACC
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
比较操作string 中 Pos1 ( 下标)开始的 Num1 个字符 与 Str 中 Off ( 下标)开始 Count
个字
符
int compare( size _ type _Pos1 , size _ type _Num1 , const basic _
string& _Str );
int compare( size _ type _Pos1 , size _ type _Num1 , const value _
type* _Ptr ) const;
int compare( size _ type _Pos1 , size _ type _Num1 , const basic _
string& _Str ,
size _ type _Off , size _ type _Count );
int com1 = s.compare ( 2 , 3 , sp );
int com2 = s.com
|
标签:学习公社 |
1 string 使用
1.1 充分使用string 操作符
1.2 眼花缭乱的string find 函数
1.3 string insert, replace, erase 2 string 和 C风格字符串
3 string 和 Charactor Traits
4 string 建议
5 小结
6 附录前言: string 的角色
C++
语言是个十分优秀的语言,但优秀并不表示完美。还是有许多人不愿意使用C或者C++,为什么?原因众多,其中之一就是C/C++的文本处理功能太麻烦,用起来很不方便。以前没有接触过其他语言时,每当别人这么说,我总是不屑一顾,认为他们根本就没有领会C++的精华,或者不太懂C++,现在我接触perl,
php, 和Shell脚本以后,开始理解了以前为什么有人说C++文本处理不方便了