这个例子里面重要是字符串的N种构造方法。
// Example16_1str1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
int main()
{
using namespace std;
string one("Lottery Winner");//ctor1 :创建一个初始化为"Lottery Winner"的字符串
cout <<"ctor1:"<< one << endl;
string two(20,'$'); //ctor2:创建一个包含20个$的字符串
cout << "ctor2:" << two << endl;
string three(one);//ctor3:复制构造函数
cout << "ctor3:" << three << endl;
one += " Oops";// overload +=
cout << one << endl;
two = "Sorry! That was ";
three[0] = 'P';
cout << two << endl;
cout << three << endl;
string four;//ctor 4:创建一个字符串,长度为0
four = two + three;// overload + ,=
cout <<"ctor4:" << four << endl;
char alls[] = "All's well that ends well";
string five(alls,20);//ctor5 :用一个字符串来初始化,只取前面的20个字符
cout << "ctor5:" << five << endl;
string six(alls+6,alls+10);//ctor6:初始化为alls的区间【begin,end】在内的字符,包括begin,不包括end
cout << "ctor6:" << six << endl;
string sixagain(&five[6],&five[10]);// ctor6 again
cout << "ctor6 again:" << sixagain << endl;
string eight1(four, 7);//ctor7:初始化为four的 从7开始的 16个字符
cout << "ctor7:from position to the end:" << eight1 << endl;
string eight2(four,7,16);//ctor7:初始化为four的 从7开始的 16个字符
cout << "ctor7:from 7 to begin ,16 characters:" << eight2 << endl;
return 0;
}
本文通过实例演示了C++中标准库字符串的各种构造方法,包括使用初始值、字符重复、字符串复制、特定范围内的字符以及从其他字符串指定位置开始等不同方式创建字符串。

被折叠的 条评论
为什么被折叠?



