[學習筆記][C++Primer Plus]String類的使用

來源:互聯網
上載者:User
1.構造字串

//1. string(const char * s)

string one("This is a string");

cout << one << endl;

 

//2. string(size_type n, char c)

string two(20,'$');

cout << two << endl;

 

//3.string(const string &str, string size_type pos=0, size_type n = npos)

string three(one);

cout << three << endl;

 

one += ". hello world";

cout << one << endl;

 

two = "Change two";

cout << two << endl;

 

three[0] = 'P';

cout << three << endl;

 

//4. string()

string four;

four = two + three;

cout << four << endl;

 

//5. string(const char *s, size_type n)

char alls[] = "abcdefghijklmnopqrstuvwxyz";

string five(alls,20);

cout << five << endl;

 

//6. template<class Iter)

//7. string(Iter begin, Iter end)

string six(alls+6,alls+10);

cout << six << endl;

 

string seven(&five[6], &five[10]);

cout << seven << endl;

輸出結果如下:

This is a string
$$$$$$$$$$$$$$$$$$$$
This is a string
This is a string. hello world
Change two
Phis is a string
Change twoPhis is a string
abcdefghijklmnopqrst
ghij
ghij
Press any key to continue

2.輸入字串

    // C風格的字串,如果長度大於10會怎麼樣?

    /*

    char info[10];

    cin >> info;

    cin.getline(info,10);

    cin.get(info, 10);

    */

 

    string word;

    cout << "Enter a line: ";

    cin >> word;

    while(cin.get()!='\n')

    {

        continue;

    }

    cout << word << " is all I wanted." << endl;

 

    string line;

    cout << "Enter a line (really!): ";

    getline(cin, line); // 使用getline(istream &, string &)

    cout << "Line: " << line << endl;

輸出結果:

Enter a line: aaaaa bbbbb ccccc ddddddd
aaaaa is all I wanted.
Enter a line (really!): aaaaa bbbbb ccccc ddddddd
Line: aaaaa bbbbb ccccc ddddddd

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.