1.1 string类型简介
string类型为C++标准库中的类型,代表一个可变长字符串。
1.2 string类型的用法
1.2.1 定义和初始化string类型对象
int main() {
string s1; //默认初始化,此时s1="",即空串
string s2 = "I love China!"; //把字符串I love China!拷贝到s2的一段内存中,不包含末尾的\0
string s3("I love China!");
string s4 = s2; //把s2内存中的内容拷贝到s4代表的一段内存中
string s5(6, 'a'); //aaaaaa, 不推荐,会创建临时对象a
}
1.2.2 判断string对象是否为空
int main() {
string s1; //默认初始化,此时s1="",即空串
if (s1.empty()) //empty判断是否为空,返回bool值
{
cout << "empty" << endl; //empty
}
}
1.2.3 返回string对象的长度
int main() {
string s1 = "";
cout << s1.size() << endl; //0, 拷贝时不包含\0
string s2 = "I love China!";
cout << s2.size() << endl; //13
cout << s2.length() <<endl; //13
}
1.2.4 返回string对象的指定位置字符
s[n]:返回s中第n个字符,n为整型,从0开始到size()- 1,如果超出范围会产生不可预测的结果。
int main() {
string s1 = "";
cout << s1[5] << endl; //乱码,访问越界
}
int main() {
string s1 = "I love China!";
cout << s1[2] << endl; // l
//修改string对象的值
s1[2] = 'D';
cout << s1 << endl; //I Dove China!
}
1.2.5 string对象的拼接
int main() {
string s1 = "abcd";
string s2 = "efg";
string s3 = s1 + s2; //s1 + s2返回一个新的string对象
cout << s3 << endl; //abcdefg
}
1.2.6 字面值和string相加
int main() {
string s1 = "abc";
string s2 = "defg";
string s3 = s1 + " and " + s2;
cout << s3 << endl; //abc and defg
//string s4 = "abc" + "def"; //错误
string s5 = "abc" + s1 + "def"; //正确
//string s6 = "abc" + "def" + s1; //错误, 两个字符串不可挨着相加
}
1.2.7 string对象的赋值
s1 = s2,字符串对象赋值,用s2里的内容取代原来s1的内容
int main() {
string s1 = "abcd";
string s2 = "efg";
s1 = s2;
cout << s1; //efg
}
1.2.8 判断string对象是否相等,大小写敏感
int main() {
string s1 = "abc";
string s2 = "abc";
string s3 = "Abc";
if (s1 == s2)
cout << "s1==s2" << endl;
if (s1 != s3)
cout << "s1!=s3" << endl;
}
1.2.9 范围for对string的使用
int main() {
string s1 = "I love China";
for (auto c : s1) //auto自动类型推导
{
cout << c; //每次输出一个字符
}
}
int main() {
string s1 = "I love China";
for (auto &c : s1) //auto自动类型推导
{
c = toupper(c); //因为c是一个引用,此时会改变s1的值
}
cout << s1; //I LOVE CHINA
}