c++ 字符串初始化和赋值

本文详细介绍了如何使用std::string进行字符串的多种初始化方式,包括默认构造、C-string、拷贝构造、缓冲区、重复字符、迭代器以及brace-enclosedinitializer等,并展示了各种赋值方法,如赋值运算符、assign函数和迭代器范围等。
摘要由CSDN通过智能技术生成

std::string 提供的字符串操作非常灵活,可以适应不同的使用场景。当你需要使用不同方式进行字符串的初始化和赋值时,可以根据需要选择适当的方法。

欢迎大家补充说明!!!

初始化 std::string

默认构造函数 - 创建一个空字符串
std::string s1;  // s1 是一个空字符串
从 C-string 初始化 - 使用字符数组或字符串字面量
const char* cstr = "Hello";
std::string s2(cstr);  // 使用 C-style 字符串初始化
std::string s3("World");  // 使用字符串字面量初始化
拷贝构造函数 - 从另一个 std::string 实例复制
std::string s4(s3);  // 使用另一个 std::string 对象初始化
从缓冲区初始化 - 使用字符数组的一部分
char buf[] = "Sample text";
std::string s5(buf, 6);  // 使用字符数组的前6个字符初始化
用重复字符初始化
std::string s6(5, 'a');  // 创建一个包含5个 'a' 的字符串:"aaaaa"
使用迭代器初始化 - 从另一个容器复制
std::vector<char> vec = {'H', 'i', '!'};
std::string s7(vec.begin(), vec.end());  // 使用字符向量初始化字符串
使用 brace-enclosed initializer
std::string s8{'C', '+', '+'};  // 使用初始化列表初始化字符串

赋值给 std::string

使用赋值运算符
std::string str;
str = "Hello, World!";  // 使用 C-style 字符串赋值
assign 成员函数
str.assign("New Value");  // 使用 C-style 字符串赋予新值
拷贝赋值
std::string other = "Example";
str = other;  // 使用另一个 std::string 对象赋值
使用迭代器范围
std::vector<char> vec = {'X', 'Y', 'Z'};
str.assign(vec.begin(), vec.end());  // 使用迭代器范围赋值
字符串拼接
std::string first = "Hello";
std::string second = "World";

first += ", ";          // 添加一个字符串字面量
first += second;        // 添加另一个 std::string
first.append("!");      // 使用成员函数 append 添加
first.push_back('.');   // 添加单个字符
  • 18
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淘气の小狼人¹º²⁴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值