简体   繁体   English

如何在C ++的basic_string内部具有空值

[英]How have null value inside basic_string in c++

Is there a way to have and process null value inside std::basic_string ? 有没有办法在std::basic_string拥有并处理null值?

Sometimes the string sequence being passed has null values. 有时传递的字符串序列具有空值。 For example below code outputs 1234,5678 instead of whole string. 例如,下面的代码输出1234,5678而不是整个字符串。

#include <iostream>
#include <string>
#include <cstring>
int main ()
{
   int length;
   std::string str = "1234,5678\000,ABCD,EFG#";
   std::cout << "length"<<str.c_str();
}

I need to get the complete string. 我需要获取完整的字符串。

First, you'll have to tell the string constructor the size; 首先,你必须告诉字符串构造函数的大小; it can only determine the size if the input is null-terminated. 它只能在输入为空终止时确定大小。 Something like this would work: 像这样的东西会起作用:

std::string str("1234,5678\000,ABCD,EFG#", sizeof("1234,5678\000,ABCD,EFG#")-1);

There's no particularly nice way to avoid the duplication; 没有特别好的方法来避免重复; you could declare a local array 你可以声明一个本地数组

char c_str[] = "1234,5678\000,ABCD,EFG#"; // In C++11, perhaps 'auto const & c_str = "...";'
std::string str(c_str, sizeof(c_str)-1);

which might have a run-time cost; 这可能会产生运行时间成本; or you could use a macro; 或者你可以使用宏; or you could build the string in pieces 或者您可以将字符串分段

std::string str = "1234,5678";
str += '\0';
str += ",ABCD,EFG#";

Finally, stream the string itself (for which the size is known) rather than extracting a c-string pointer (for which the size will be determined by looking for a null terminator): 最后,流式传输字符串本身(其大小已知)而不是提取c字符串指针(其大小将通过查找空终止符来确定):

std::cout << "length" << str;

UPDATE: as pointed out in the comments, C++14 adds a suffix for basic_string literals: 更新:正如评论中指出的,C ++ 14为basic_string文字添加了一个后缀:

std::string str = "1234,5678\000,ABCD,EFG#"s;
                                           ^

which, by my reading of the draft standard, should work even if there is an embedded null character. 根据我对标准草案的阅读,即使存在嵌入的空字符,它也应该起作用。

You can do this with std::string(std::initalizer_list<char> il) it's just a little bit of a pain in the neck: 你可以用std::string(std::initalizer_list<char> il)做到这一点,这只是脖子上的一点点痛苦:

string str{'1', '2', '3', '4', ',', '5', '6', '7', '8', '\0', '0', '0', ',', 'A', 'B', 'C', 'D', ',', 'E', 'F', 'G', '#'};
cout << "length: " << str.size() << ": " << str;

Outputs: 输出:

length: 22: 1234,567800,ABCD,EFG# 长度:22:1234,567800,ABCD,EFG#

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM