zoukankan      html  css  js  c++  java
  • [学习笔记][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



  • 相关阅读:
    11.28 正则表达式
    12.28jQuery 的取值赋值
    11.27 上传下载 图片预览
    11.28 验证控件
    12.23,repeater 分页显示
    12.23,搜索标记
    1.基础CRUD
    C#杀进程与之之子进程
    使用procedump捕获未处理异常的dump
    [.net core] 12.环境变量
  • 原文地址:https://www.cnblogs.com/xuzhong/p/394433.html
Copyright © 2011-2022 走看看