一个std :: string包含嵌入的null? [英] Can a std::string contain embedded nulls?

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

问题描述

对于常规C字符串,一个空字符'\0'表示数据的结尾。



std :: string ,我可以有一个带有嵌入空字符的字符串吗?

解决方案

是的,您可以在 std :: string 中嵌入null。



示例:

  std :: string s; 
s.push_back('\0');
s.push_back('a');
assert(s.length()== 2);

注意: std :: string c_str()成员将总是在返回的char缓冲区附加一个空字符;但是, std :: string data()成员可以或不可以在返回的字符



有一件事要注意:不要在RHS上使用 operator + = char *



例如:

  std :: string s =hello; 
s + =\0world;
assert(s.length()= 5);

正确的方式:

  std :: string s =hello; 
s + = std :: string(\0world,6);
assert(s.length()== 11);

存储更常见的二进制数据以使用std :: vector



一般来说,使用 std :: vector 来存储任意二进制数据更为常见。

  std :: vector< char> f 
buf.resize(1024);
char * p =& buf.front();

这可能更常见,因为 std :: string 使用& buf.front()可以直接修改缓冲区的内容。


For regular C strings, a null character '\0' signifies the end of data.

What about std::string, can I have a string with embedded null characters?

解决方案

Yes you can have embedded nulls in your std::string.

Example:

std::string s;
s.push_back('\0');
s.push_back('a');
assert(s.length() == 2);

Note: std::string's c_str() member will always append a null character to the returned char buffer; However, std::string's data() member may or may not append a null character to the returned char buffer.

Be careful of operator+=

One thing to look out for is to not use operator+= with a char* on the RHS. It will only add up until the null character.

For example:

std::string s = "hello";
s += "\0world";
assert(s.length() == 5);

The correct way:

std::string s = "hello";
s += std::string("\0world", 6);
assert(s.length() == 11);

Storing binary data more common to use std::vector

Generally it's more common to use std::vector to store arbitrary binary data.

std::vector<char> buf;
buf.resize(1024);
char *p = &buf.front();

It is probably more common since std::string's data() and c_str() members return const pointers so the memory is not modifiable. with &buf.front() you are free to modify the contents of the buffer directly.

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

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