你如何构造一个带有嵌入空值的 std::string ?

How do you construct a std::string with an embedded null?(你如何构造一个带有嵌入空值的 std::string ?)

本文介绍了你如何构造一个带有嵌入空值的 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::stringNOT 终止的(如其他帖子中所建议的那样).但是,您可以使用 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.

这篇关于你如何构造一个带有嵌入空值的 std::string ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:你如何构造一个带有嵌入空值的 std::string ?

基础教程推荐