[学习笔记][C++Primer Plus]String类的使用

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



原文地址:https://www.cnblogs.com/xuzhong/p/394433.html