c++ 字符串初始化和赋值
c++ 字符串初始化和赋值
·
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('.'); // 添加单个字符
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)