小工具知识网

当前位置: 首页 > 行业知识 > 【C++】string类的使用②(容量接口Capacity || 元素获取Element access)

行业知识

【C++】string类的使用②(容量接口Capacity || 元素获取Element access)

2026-10-31 09:33:31 来源:互联网转载

个人主页: Forcible Bug Maker

专栏: STL || C++

目录

  • 前言
  • 容量接口(Capacity)
    • ==size和length==
    • ==capacity==
    • ==max_size==
    • ==reserve==
    • ==resize==
    • ==clear==
    • ==empty==
    • ==shrink_to_fit==
    • 元素获取(Element access)
      • ==operator[ ]==
      • ==at==
      • ==back和front==
      • 结语

        前言

        本篇博客主要内容:STL库中string的容量接口(Capacity)和四种元素获取方式(Element access)的介绍和使用。

        来到string类的使用第二篇,让我们接着上一篇来讲。

        容量接口(Capacity)

        size和length

        size_t size() const;

        size_t length() const;

        将这两个函数接口的功能完全相同,它们没有参数传递,只有一个返回值(且这个返回值是const类型,不能被改变),返回:string对象中串的长度。

        使用样例:

        #include #include using namespace std;int main(){string str("Test string");// string::sizecout string str("Test string");cout string str("Test string");cout     string str("hello world");    cout string str("hello world");cout string str("hello world");cout string str1("hello world");string str2;cout     // operator[]    string str("Test string");    str[1] = 'T';    for (int i = 0; i 

上一篇:mc手机版怎么加入服务器?

下一篇:店铺怎么挂服务器上面?