string strs //生成空字符串
string s(str) //生成字符串str的复制品
string s(str, stridx) //将字符串str中始于stridx的部分作为构造函数的初值
string s(str, strbegin, strlen) //将字符串str中始于strbegin、长度为strlen的部分作为字符串初值
string s(cstr) //以C_string类型cstr作为字符串s的初值
string s(cstr,char_len) //以C_string类型cstr的前char_len个字符串作为字符串s的初值
strings(num, c) //生成一个字符串,包含num个c字符
strings(strs, beg, end) //以区间[beg, end]内的字符作为字符串s的初值
string str("hello world");
string str2(str); //拷贝构造
string str3(str, 5);//在str中取5个字符存在str3
string str4(str, 6, 10);//取出6到10字符
const char* arr = "hello world";
string str5(arr); //将const char* 类型赋值给str5
string str6(arr, 5);//将const char* 前五个字符赋值给str6;
string str7(6, 'W'); //给str7初始化为6个W
string str8(str.begin(), str.end()); //复制字符串 str 的所有元素,并赋值给 str8
类型转换
//string 转 char *
std::string str = "string";
//方法1
char* chr = const_cast<char*>(str.c_str());
//方法2
char* cstr = &str[0];
//string 转 const char *
const char* c_str = str.c_str();
//char数组 转 string
char arr[] = "hello world";
string s_arr = arr;
//char * 转 string
char* p = &str[0]; //方法二给char * 赋初值
string s_p = p;
//const char * 转 string
const char* pt = "hello";
string s_pt = pt;
//const char * 和 char *
const char* src = "this is a const exp";
char* ch = const_cast<char*>(src);
const char* dst = static_cast<const char*>(ch);
cout << ch << endl;
cout << dst << endl;
//string转为char[];
//char[]可以直接赋值给stiring
//string不能直接转换为char[],可以先转换为char*,再通过strcpy来转换
char buf[32];
char* p = const_cast<char*>(str.c_str());
strcpy(buf, p);