你如何构造一个带有嵌入空值的 std::string ?
如果我想用如下一行构造一个 std::string:
If I want to construct a std::string with a line like:
std::string my_string("ab");
如果我想在结果字符串中包含三个字符(a、null、b),我只得到一个.正确的语法是什么?
Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?
推荐答案
自 C++14
我们已经能够创建文字std::string
#include <iostream>
#include <string>
int main()
{
using namespace std::string_literals;
std::string s = "pl--op"s; // <- Notice the "s" at the end
// This is a std::string literal not
// a C-String literal.
std::cout << s << "
";
}
在 C++14 之前
问题是采用 const char*
的 std::string
构造函数假定输入是 C 字符串.C 字符串被 终止,因此当它到达
字符时解析停止.
Before C++14
The problem is the std::string
constructor that takes a const char*
assumes the input is a C-string. C-strings are terminated and thus parsing stops when it reaches the
character.
为了弥补这一点,您需要使用从 char 数组(不是 C 字符串)构建字符串的构造函数.这需要两个参数 - 一个指向数组的指针和一个长度:
To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length:
std::string x("pqrs"); // Two characters because input assumed to be C-String
std::string x("pqrs",5); // 5 Characters as the input is now a char array with 5 characters.
注意:C++ std::string
是 NOT 终止的(如其他帖子中所建议的那样).但是,您可以使用
c_str()
方法提取指向包含 C 字符串的内部缓冲区的指针.
Note: C++ std::string
is NOT -terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method
c_str()
.
另请查看 Doug T 的回答 下面关于使用 vector
.
Also check out Doug T's answer below about using a vector<char>
.
另请查看 RiaD 以获取 C++14 解决方案.
Also check out RiaD for a C++14 solution.
相关文章