学习笔记:string类
发布日期:2021-05-14 16:30:21 浏览次数:14 分类:精选文章

本文共 1246 字,大约阅读时间需要 4 分钟。

前言

郭炜老师视频笔记

一、string类

错误的初始化方法:

  • string error1 = ‘c’;
  • string error2 = (‘u’);
  • string error3 = 22;
  • string error4(8);

可以将字符串赋值给string对象:

  • string s1;
  • s = ‘n’;
  • string month = “month”;
  • string s2(8, ‘x’); // 输出为:xxxxxxxx
  • string s3 = “hello”;

二、string成员函数

  • string对象的长度用成员函数length()获取

    string s("hello");
    cout << s.length();
  • string支持流读取运算符

    string stringObject;
    cin >> stringObject;
  • string支持getline()函数

    string s;
    getline(cin, s);
  • 比较大小compare

    string s1("hello"), s2("hello"), s3("hell");
    int f1 = s1.compare(s2); // 0
    int f2 = s1.compare(s3); // 1
    int f3 = s3.compare(s1); // -1
    int f4 = s1.compare(1, 2, s3, 0, 3); // 1
    int f5 = s1.compare(0, s1.size(), s3); // 0

    输出结果:

    0
    1
    -1
    -1
    1

  • 成员函数substr

    string s1("hello world"), s2;
    s2 = s1.substr(4, 5); // 输出:world
  • 寻找string中的字符

    string s1("hello worlld");
    s1.find("ll", 1); // 2
    s1.find("ll", 2); // 2
    s1.find("ll", 3); // 9
  • 成员函数find_first_of()

    string s1("hello world");
    s1.find_first_of("abcd"); // 2 (d)
  • 删除erase()

    string s1("hello world");
    s1.erase(5); // 输出:hell
  • 替换replace(),插入insert()

    string s1.replace(4, 5, "wor"); // 替换子串  
    string s2.insert(2, "World"); // 插入World在位置2
  • 转换成C语言式char*字符串

    string s1("hello world");
    cout << s1.c_str(); // 输出:hello world
  • 总结

    当要使用String库的时候,直接搜......
    上一篇:笔记:python filter()
    下一篇:学习笔记:c++数据结构——队列

    发表评论

    最新留言

    路过按个爪印,很不错,赞一个!
    [***.219.124.196]2025年04月07日 19时46分58秒

    关于作者

        喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
    -- 愿君每日到此一游!

    推荐文章