我可以在C ++中使用支持嵌入式NULL字符的字符串吗?
我的问题是: 构造具有嵌入式NULL的字符串,因此将其作为字节数组发送到C ++ DLL。
string inputStr("he\0llo", 6);
int byteLength = 6;
BYTE *inputByte = (BYTE*)(char*)inputStr.c_str();
ApplyArabicMapping(inputByte , byteLength);
答案 0 :(得分:2)
是的,std::string
支持存储NULL
个字符,因为它不是NULL
- 已终止。您可以通过多种方式创建一个:
string str("he\0llo", 6);
str.append(1, '\0');
str.push_back('\0');
const char[] cstr = "hell\0o";
string str2(cstr, cstr + sizeof(cstr) - 1); // - 1 for the NULL
答案 1 :(得分:2)
您可以使用计数字符串,其中字符缓冲区与其“内容长度”一起存储;这允许你嵌入任何角色。例如,std::string
是一种计数字符串。
显然,你不能将这样的字符串传递给需要经典C字符串的函数,因为它会看到它遇到的第一个null作为字符串终止符。