string的构造函数
string函数的初始化
/*
>Plan:string的初始化
>Author:ADiiana
>Time:2019/03/17
*/
#include<iostream>
#include<string>
using namespace std;
int main(){
std::string s0("Initial string");
// constructors used in the same order as described above:
string s1;
string s2(s0);
string s3(s0, 8, 3); //从s0的第8个字符开始,取3个字符构造s3
string s4("A character sequence");
string s5("Another character sequence", 12); //取该字符串的12个字符构造s5
string s6a(10, 'x'); //将s6a初始化为10个x
string s6b(10, 42); // 42 is the ASCII code for '*',同上
string s7(s0.begin(), s0.begin() + 7); //从s0的第1个字符开始,取7个字符构造s7
string s8[] = { "hello123", "world" }; //初始化一个string数组,这个数组的每一个元素都是string对象
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl;
cout << "s4: " << s4 << endl;
cout << "s5: " << s5 << endl;
cout << "s6a: " << s6a << endl;
cout << "s6b: " << s6b << endl;
cout << "s7: " << s7 << endl;
cout << "s8: " << s8[0] << " " << s8[1] << endl;
//cout << s8[1].size() << endl;
system("pause");
return 0;
}
输出:
string的析构函数不需要我们调用
string的opertor=函数
/*
>Plan:string的opetor=
>Author:ADiiana
>Time:2019/03/17
*/
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1, str2, str3;
str1 = "Test string: "; // c-string
str2 = 'x'; // single character
str3 = str1 + str2; // string
//string str4 = 'x'; //编译错误,不能用char类型初始化string,只能赋值。
string str5 = "hello world"; //正确
cout << str3 << endl;
cout << str5 << endl;
system("pause");
return 0;
}
输出: