如何构造一个带有嵌入式null的std :: string? [英] How do you construct a std::string with an embedded null?

查看:242
本文介绍了如何构造一个带有嵌入式null的std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想构造一个带有如下行的std :: string:

  std :: string my_string \0b); 

我想在结果字符串(a,null,b)中有三个字符,得到一个。正确的语法是什么?

解决方案

问题是 std :: string 构造函数,它接受一个 const char * 假设输入是一个C字符串。 C字符串 \0 终止,因此解析在到达 \0 字符时停止。



为了弥补这一点,您需要使用从char数组(而不是C-String)构建字符串的构造函数。这需要两个参数 - 指向数组的指针和长度:

  std :: string x(pq \0rs ); //两个字符,因为输入假设为C-String 
std :: string x(pq\0rs,5); // 5字符作为输入现在是一个有5个字符的字符数组。

注意:C ++ std :: string NOT \0 - 已终止(如其他帖子中所建议)。但是,您可以使用方法 c_str()提取包含C字符串的内部缓冲区的指针。

另请参阅 Doug T的回答

a>


If I want to construct a std::string with a line like:

std::string my_string("a\0b");

Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?

解决方案

The problem is the std::string constructor that takes a const char* assumes the input is a C-string. C-strings are \0 terminated and thus parsing stops when it reaches the \0 character.

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("pq\0rs");   // Two characters because input assumed to be C-String
std::string   x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters.

Note: C++ std::string is NOT \0-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().

Also check out Doug T's answer below about using a vector<char>.

这篇关于如何构造一个带有嵌入式null的std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆