/*
标准库类型string表示可变长的字符序列
使用string类型首先包含string头文件
string定义在命名空间std中
定义和初始化string对象
*/
#include <string>
#include <iostream>
using
std::string;
using
std::cout;
using
std::cin;
using
std::endl;
int
main(){
auto
a = 10;
cout<<
"中文auto a="
<<a<<endl;
string s1;
//默认初始化,是一个空字符串
string s2 = s1;
//s2是s1的副本
string s3=
"hello world!!!"
;
//s3是字符串字面值的副本,拷贝初始化
string s4(10,
'v'
);
//直接初始化
string s5(10,
'a'
);
//直接初始化
string s6(
"adfg"
);
//s6是字面值"adfg"的副本,除了字面值最后的那个空字符外
string s7=
"value"
;
//等价于string s6("adfg");
//直接初始化和拷贝初始化
cout<<
"s1="
<<s1<<
"\n"
<<
"s2="
<<s2<<
"\n"
<<
"s3="
<<s3<<
"\n"
<<
"s4="
<<s4<<
"\n"
<<
"s5="
<<s5<<
"\n"
<<endl;
cout<<
"s6="
<<s6<<
"\n"
<<endl;
cout<<
"s7="
<<s7<<
"\n"
<<endl;
/*
s1=
s2=
s3=hello world!!!
s4=vvvvvvvvvv
s5=aaaaaaaaaa
*/
//读写string对象
string ss;
cin>>ss;
//将string对象读入ss,遇到空白停止(按回车键)
cout<<ss<<endl;
//读取未知数量的字符串
string word;
//while(cin>>word){ //按ctrl+c可以结束
// cout<<word<<endl;
//}
//使用getline读取一整行
//string line;
//while(getline(cin,line)){
// cout<<line<<endl;
//}
if
(s1.empty()){
cout<<
"s1 is empty!!"
<<endl;
}
cout<<
"s7--length=="
<<s7.size()<<endl;
//size函数返回值类型为string::size_type
string::size_type len = s6.size();
cout<<
"s6--length=="
<<len<<endl;
//两个string对象相加
string add1=
"123"
,add2=
"456"
;
cout<<
"plus result="
<<add1+add2<<endl;
//string对象和字面值相加
string add3=
"789"
;
cout<<
"plus result="
<<add3+
"98765"
<<endl;
//不能把两个字面值直接相加(编译不能通过)
//cout<<"result===="<<"sdsd"+"sbsb"<<endl;
//使用范围for循环处理字符串
string str(
"some thing"
);
for
(
auto
c:str){
cout<<c<<endl;
}
//使用下标或索引访问string对象
if
(!str.empty()){
str[0] =
toupper
(str[0]);
cout<<
"使用下标访问string对象,并改变第一个字符为大写"
<<str<<endl;
}
return
0;
}