我有一个奇怪的带有 0x0 的字符串,有人可以帮我吗?
string a = funxx(); // funxx is a external func from Crypto++ libary
string b = "test"
如果我打印出a和b的内容,它们都显示为“test”
a.size() is: 5
b.size() is: 4
a.length() is: 5
b.length() is: 4
for( int i = 0; i < a.size(); i++ ) {
cout << "0x" << hex << (0xFF & static_cast<byte>(a[i])) << " ";
}
print out: 0x74 0x65 0x73 0x74 0x0
for( int i = 0; i < b.size(); i++ ) {
cout << "0x" << hex << (0xFF & static_cast<byte>(b[i])) << " ";
}
print out: 0x74 0x65 0x73 0x74
我的问题是,为什么 a.length()
和 a.size()
返回 5
而不是 4
,如何让a
和b
相等?
总结:
感谢您的大量回复。我认为现在问题对我来说很清楚了。来自 Crypto++ 库的外部 func
在字符串中返回一个额外的空字符,并且在字符串中,长度被单独跟踪。
我需要做的是 std::string(a.c_str())
最佳答案
从 std::string
中删除尾随 null 的简单方法:
if (!str.empty() && *str.rbegin() == 0)
str.resize(str.size() - 1);
关于带有额外 0x0 的 C++ 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049844/