标准库类型string表示可变长的字符序列,使用string必须包含string头文件。
#include<string>
using std::string;
1、定义和初始化
string s;//空字符串s
string s1=s;//s1是s的副本
string s2="Hello CSDN Blog";//s2是字符串常量的副本
string s3(100,'u');//用100个'u'初始化
2、string对象操作
从cin中读取string
string str;
cin>>str;
cout<<str<<endl;
读取未知的string对象
string s;
while(cin>>s)//反复读取直到文件末尾
cout<<s<<endl;
使用getline读取一整行
string line;
while(getline(cin,line))
if(!line.empty())//每次读取一整行,遇到空行直接跳过
cout<<line<<endl;
两个string对象可以进行比较,赋值,相加的操作。也可以将string于常量字符串相加
string s1=s+"we are you";
3、处理string对象中的字符
使用库函数处理string字符
#include<cctype>
isallnum(c);//检测数字
isalpha(c);//检测字母
isdigit(c);//检测数字
islower(c);//检测小写字母
isounct(c);//检测标点符号
tolower(c);//全转换为小写字母
toupper(c);//全转换为大写字母tring中的每个字符
输出string中的每个字符
//C++11方法
string str("something happens");
for(auto c:str)
cout<< c <<endl;
//或者,老方法
for(int i=0;i<str.size();i++)
cout<<str[i]<<endl;