标准库类型string类
首先定义和初始化string对象有以下几种方式:
string a1;
string a2=a1;
string a3="Hello"; //拷贝初始化
string a4=(10,'S');
string a5=("World"); //直接初始化
string a6=(a1);
对string类对象操作还要有相应的操作,主要操作如下:
os << s //将s写到输出流os当中,返回os
is >> s //从is中读取字符串赋给s,字符串以空格分隔,返回is
getline(is, s) //从is中读取一行赋给s,返回is
s.empty() //s为空返回true,否则false
s.size() //返回s中字符的个数
s[n] //返回字符s中第n个字符
s1+s2
s1==s2
s1!=s2
<,<=,>=,> //利用字符在字典中的顺序进行比较,且对字母的大小写敏感
string对象操作实例:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int m;
string s1("abcdefg");
cout << "s1=" <<s1<<endl<<endl;
cout << "!!!!!s1=" <<s1[3]<<endl<<endl;
string s2=string(10,'d');
cout << "s2=" <<s2<<endl<<endl;
string s3;
s3=s1+s2;
cout << "s3=" <<s3<<endl<<endl;
m=s1.size();
cout << "s1长度: "<<m<<endl<<endl;
if(!s1.empty()){
cout<<"Hello"<<endl<<endl;
}
string s4=(s1+", ")+"world";
cout <<"s4="<<s4<<endl<<endl;
string s5;
cout << "Please enter character string" <<endl;
getline(cin,s5);
cout <<"s5="<<s5<< endl<<endl;
return 0;
}
对string对象赋值中可以直接赋值也可将一对象的值赋给另外一个对象的值,如string a("ABCDEF"),b; b=a;而后相加操作可以两个对象相加(string a=“C++”,b=“primer”;string c=a+b;),也可以字面值和string对象相加,但是要注意不能直接将字面值相加而应string对象和字面值相加,如:
string s2="C++";
string s1=s2+","+"Primer"; //正确
string s3="Hello"+","+s1; //错误
string对象中的字符处理应用很广泛,那么其对应的操作也相当多,下面是cctype头文件中的函数一览表:
isalnum(c) //假如c是字母或数字,则为true
isalpah(c) //假如c是字母,则为true
iscntrl(c) //假如c是控制字符,则为true
isdigit(c) //假如c是数字,则为true
isgraph(c) //假如c不是空格,则为true
islower(c) //假如c是小写字母,则为true
isprint(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对象中的单个字符有两种方式:
<1>使用下标
string str("Hello C++ Primer");
if(!str.empty())
str[6]=tolower(str[6]);
cout << str[6] << endl;
<2>使用迭代器
<em>string str1="Hello C++ Primer";
string::size_type punct_cnt = 0;
for(string::size_type i=0;i!=str1.size();++i)
{
if(ispunct(str1[i]))
++punct_cnt;
str1[i]=toupper(str1[i]);
}
cout<<"字符中标点符号共有:"<<punct_cnt<<endl;
cout<<str1<<endl; </em>
也可利用下标随机访问string对象中的任意字符
#include <iostream>
using namespace std;
int main()
{
string str1="0123456789ABCDEF";
string::size_type punct_cnt;
string str2;
while(cin >> punct_cnt)
if(punct_cnt < str1.size())
str2 += str1[punct_cnt];
cout<<str2<<endl;
return 0;
}
C++II新标准中提供了基于范围的for语句,这种语句bain里给定序列中的每个元素并对序列鲜红的每个值执行操作,语法
for (declaration:expression);
string str="Hello world!!";
for(auto ch:str)
cout << ch << endl;