C++ string 类的基础用法详解

一、为什么要学习 C++ 的 string?

C 语言中的字符串有什么问题?

C 语言使用的是 字符数组 + '\0' 结尾 的字符串形式,比如:

char s[] = "hello";

但它有几个缺点:

  • 需要手动管理空间(容易越界、内存泄漏)

  • 处理字符串必须依赖一堆 strXXX 函数(如 strlen、strcpy 等)

  • 字符串本身和操作函数是分离的,不符合 C++ 的面向对象思想

C++ 的 string 类解决了这些问题:

✔ 自动管理空间
✔ 直观、简单的字符串操作
✔ 内置大量成员函数
✔ 支持迭代器和范围 for,更现代、更安全

二、string 的常见构造方式(非常重要)

写法含义
string s1;空字符串
string s2("hello");用 C 字符串构造
string s3(s2);拷贝构造
string s4(5, 'x');“xxxxx”,5 个字符 x
string s1;              // 空串
string s2("hello");     // 由C字符串构造
string s3(s2);          // 拷贝构造
string s4(5, 'x');      // s4 = “xxxxx”

三、string 的常用访问方式

下标访问(operator[])

string s = "hello";
cout << s[1];   // e
s[2] = 'X';      // 修改字符

迭代器访问(begin / end)

for (auto it = s.begin(); it != s.end(); ++it)
{
    cout << *it << " ";
}

反向迭代器(rbegin / rend)

for (auto it = s.rbegin(); it != s.rend(); ++it)
{
    cout << *it << " "; // 从末尾向前打印
}

范围 for(最简单)

for (auto ch : s)
{
    cout << ch << " ";
}

四、string 的常用成员函数(最实用的几个)

size(), length()

返回有效字符数量(两个等价)

cout << s.size();
cout << s.length();

empty()

判断是否为空(空返回1,非空返回0)

cout<<s.empty();

clear()

清空字符串内容

s.clear();

capacity()

返回当前分配的空间大小

cout << s.capacity();

reserve()

手动扩容,提高效率

s.reserve(100); // 提前分配空间

resize()

修改有效字符个数

string s = "hello";
s.resize(10, 'x');    // 变为 "helloxxxxx"
s.resize(3);          // 变为 "hel"

五、为什么要学习 auto 和 范围 for?

auto:自动类型推导

auto x = 10;      // int
auto p = &x;      // int*
auto it = s.begin(); // string::iterator

注意:

  • auto 声明引用必须写成 auto&

  • 同一行声明多个 auto 变量必须类型相同

  • auto 不能作为函数参数类型

范围 for:最推荐的遍历写法

for (auto ch : s)
{
    cout << ch << " ";
}

也可以加引用(可修改内容):

for (auto& ch : s)
{
    ch = toupper(ch);
}

六、string 的使用示例(简单清晰)

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s("hello world");

    cout << s.size() << endl;      // 长度
    cout << s[1] << endl;          // 访问字符

    s[4] = 'x';                    // 修改
    cout << s << endl;

    // 普通迭代器遍历
    for (auto it = s.begin(); it != s.end(); ++it)
        cout << *it << " ";
    cout << endl;

    // 反向遍历
    for (auto it = s.rbegin(); it != s.rend(); ++it)
        cout << *it << " ";
    cout << endl;

    // 范围for
    for (auto ch : s)
        cout << ch << " ";
    cout << endl;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值