《C++ Primer Plus》16.1 string類 學習筆記

weixin_34041003發表於2016-07-16

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 << "!\n";
    string six(alls+6, alls + 10);  // ctor #6
    cout << six << endl;
    string seven(&five[6], &five[10]);  // cotr #6
    cout << seven << "...\n";
    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 \n
cin.get(info, 100);    // read a line, leave \n in queue
對於string物件,有兩種方式:
string stuff;
cin >> stuff;        // read a word
getline(cin, stuff);    // read a line, discard \n
兩個版本的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的字串。

相關文章