《C++ Primer Plus》16.1 string类 学习笔记

16.1.1 构造字符串
程序清单16.1使用了string的7个构造函数。
程序清单16.1 str1.cpp
--------------------------------------------------
// str1.cpp -- introducing the string class
#include <iostream>
#include <string>
// using string constructors

int main()
{
    using namespace std;
    string one("Lottery Winner!");  // ctor #1
    cout << one << endl;            // overloaded <<
    string two(20, '$');            // ctor #2
    cout << two << endl;
    string three(one);              // ctor #3
    cout << three << endl;
    one += " Oops!";
    cout << one << endl;
    two = "Sorry! That was ";
    three[0] = 'P';
    string four;                    // ctor #4
    four = two + three;             // overloaded +, =
    cout << four << endl;
    char alls[] = "All's well that ends well";
    string five(alls, 20);          // ctor #5
    cout << five << "! ";
    string six(alls+6, alls + 10);  // ctor #6
    cout << six << endl;
    string seven(&five[6], &five[10]);  // cotr #6
    cout << seven << "... ";
    string eight(four, 7, 16);
    cout << eight << " in motion!" << endl;
    return 0;
}
--------------------------------------------------
效果:
Lottery Winner!
$$$$$$$$$$$$$$$$$$$$
Lottery Winner!
Lottery Winner! Oops!
Sorry! That was Pottery Winner!
All's well that ends!
well
well...
That was Pottery in motion!
--------------------------------------------------
构造函数string(initializer_list<char> il)让您能够将列表初始化语法用于string类。也就是说,它使得下面这样的生命是合法的:
string piano_man = {'L', 'i', 's', 'z', 't'};
string comp_lang {'L', 'i', 's', 'p'};

16.1.2 string类输入
对于C-风格字符串,输入有3种方式:
char info[100];
cin >> info;        // read a word
cin.getline(info, 100);    // read a line, discard
cin.get(info, 100);    // read a line, leave in queue
对于string对象,有两种方式:
string stuff;
cin >> stuff;        // read a word
getline(cin, stuff);    // read a line, discard
两个版本的getline()都有一个可选参数,用于指定使用哪个字符来确定输入的边界:
cin.getline(info, 100, ':');    // read up to :, discard :
getline(stuff, ':');        // read up to :, discard :
在功能上,C-风格字符串和string的主要区别在于,string版本的getline()将自动调整目标string对象的大小,使之刚好能够存储输入的字符。

16.1.3 使用字符串
……

16.1.4 string还提供了哪些功能
……

16.1.5 字符串种类
本节将string类看作基于char类型的。事实上,正如前面指出的,string库实际上是基于一个模板类的:
template<class charT, class traits = char, traits<charT>,
    class Allocator = allocator<charT> >
basic_string {...};
模板basic_string有4个具体化,每个具体化都有一个typedef名称:
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
typedef basic_string<char16_t> u16string;   // C++11
typedef basic_string<char32_t> u32string;   // C++11
这让您能够使用基于类型wchar_t、wchar16_t、char32_t和char的字符串。

原文地址:https://www.cnblogs.com/moonlightpoet/p/5677523.html