标准库string类型

时间:2023-03-10 03:41:55
标准库string类型

一、string 对象的定义和初始化的方式

1、 string s1;

2、 string s2(s1);

3、 string s3("hello");

4、 string s4(n,'c');  //将s4初始化为字符'c'的n个副本

二、string 对象的读写

1、读入未知数目的string对象

例: int main()

{

string word;

while(cin>>word)

cout<<word<<endl;

return 0;

}

2、用getline读取整行文本

getline函数接受二个参数:一个输入流对象和一个string对象.遇到换行符停止

例:int main()

{

string line;

while(getline(cin,line))

cout<<line<<endl;

return 0;

}

三、string 对象中字符的处理

对string对象中的单个字符处理的的函数一般都在cctype头文件中

cctype中定义的函数:

isalnum(c)    //若c是字母或数字,则为true。

isalpha(c)     //若c是字母。则为true。

iscntrl(c)       //若c是控制字符,则为true。

isdigit(c)       //若c是数字,则为true。

isgraph(c)    //若c不是空格,但可打印,则为true。

islower(c)     //若c是小写字母,则为true。

ispunct(c)    //若c是标点符号,则为true。

isspace(c)    //若c是空白字符,则为true。

isupper(c)    //若c是大写字母,则为true。

isxdigit(c)     //若c是十六进制数,则为true。

tolower(c)    //若c是大写字母,则返回小写字母形式,否则直接返回c。

toupper(c)   //若c是小写字母,则返回其大写字母形式,否则直接返回c。

例:统计字符串中标点符号的个数

string s("hello world!!!!");

string::size_type punct_cnt=0;

for(string::size_type index=0;index!=s.size();+index)

if(ispunct(s[index]))

++punct_cnt;

cout<<punct_cnt<<endl;

整理一下这些东西,相信以后用得着。。。。。