C++PrimerPlus(第6版)中文版Chapter16.1str1.cpp:字符串的构造函数的N种写法

本文通过实例演示了C++中标准库字符串的各种构造方法,包括使用初始值、字符重复、字符串复制、特定范围内的字符以及从其他字符串指定位置开始等不同方式创建字符串。

这个例子里面重要是字符串的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;


}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值