std::string 进行数据流拷贝
- User
std::string 进行数据流拷贝
- Assistant
std::string 可以通过输入输出流对象进行数据流拷贝,具体实现方式是使用 std::ostream 类的插入运算符 << 将字符串插入到输出流中,或者使用 std::istream 类的提取运算符 >> 将输入流中的数据提取到字符串中。
示例代码:
#include <iostream> #include <string> int main() { std::string str = "Hello, world!"; // 数据流输出拷贝 std::cout << "str: " << str << std::endl; // 数据流输入拷贝 std::string input_str; std::cout << "请输入一个字符串:" << std::endl; std::cin >> input_str; std::cout << "您输入的字符串是:" << input_str << std::endl; return 0; }输出结果:
str: Hello, world! 请输入一个字符串: Hello 您输入的字符串是:Hello - User
std::string 进行二进制 数据流拷贝
- Assistant
std::string 也可以进行二进制数据流拷贝,具体实现方式是使用 std::memcpy 函数将二进制数据拷贝到 std::string 对象中,或者使用 std::string 的成员函数 data() 得到字符串内容的指针然后进行指针操作。
示例代码:
#include <iostream> #include <string> #include <cstring> int main() { // 二进制数据流拷贝 char binary_data[] = {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21}; std::string binary_str(binary_data, sizeof(binary_data)); std::cout << "binary_str: " << binary_str << std::endl; // 修改二进制数据 char* str_ptr = const_cast<char*>(binary_str.data()); str_ptr[0] = 0x68; std::cout << "modified binary_str: " << binary_str << std::endl; return 0; }输出结果:
binary_str: Hello, world! modified binary_str: hello, world!需要注意的是,std::string 对象内部是使用字符数组保存字符串内容的,因此可以直接拷贝二进制数据到 std::string 对象中。另外,直接操作 std::string 内部的字符数组是不安全的,因为在 C++11 之前,std::string 的成员函数 data() 返回的是 const char* 类型的指针,会阻止了对内容的修改。在 C++11 之后,data() 函数返回的是 char* 类型的指针,但仍需要注意对 std::string 对象进行修改的安全性。
- User
std::string 申请指定大小空间
- Assistant
可以使用 std::string 的成员函数 reserve() 申请指定大小的空间,reserve() 函数申请的空间不会初始化,只是增加了 std::string 对象内部的字符数组的大小。
示例代码:
#include <iostream> #include <string> int main() { std::string str = "Hello, world!"; std::cout << "capacity before reserve: " << str.capacity() << std::endl; // 申请空间 str.reserve(100); std::cout << "capacity after reserve: " << str.capacity() << std::endl; return 0; }输出结果:
capacity before reserve: 15 capacity after reserve: 100需要注意,申请的空间并不一定会完全占用 std::string 对象内部的字符数组空间,std::string 对象的内部实现方式可能导致实际使用的内存大小大于申请的空间大小,而使用 resize() 函数则可以确保占用指定大小的空间。同时,如果在申请空间后并没有填满 std::string 对象,可以使用 shrink_to_fit() 函数将不需要的空间释放掉。
- User
std::string 构建对象不包含\0
- Assistant
使用 std::string 的构造函数可以构建一个不包含 '\0' 的字符串。如果构造函数传入的字符串是字符串字面量,在字符串字面量的末尾会自动包含一个 '\0',需要特殊处理才能构建不包含 '\0' 的 std::string 对象。
示例代码:
#include <iostream> #include <string> #include <cstring> int main() { char str_data[5] = {'h', 'e', 'l', 'l', 'o'}; std::string str(str_data, sizeof(str_data)); std::cout << "str: " << str << std::endl; std::cout << "str size: " << str.size() << std::endl; char str_literal[] = "hello"; // 构建不包含 '\0' 的 std::string 对象 std::string str2(str_literal, strlen(str_literal)); std::cout << "str2: " << str2 << std::endl; std::cout << "str2 size: " << str2.size() << std::endl; return 0; }输出结果:
str: hello str size: 5 str2: hello str2 size: 5在构建不包含 '\0' 的 std::string 对象时,需要使用字符串长度作为参数,而不是 sizeof 操作符获取字符串内存大小,因为 sizeof 操作符会包含字符串字面量的末尾 '\0',从而导致构建的 std::string 对象包含 '\0'。