以下是去除字符的三个选项(如您所问),具体取决于您是否需要保持data_
完整,或者您是否只是想要一种快速简便的方法来输出字符。此外,最后一个选项显示了一种将不同(单个)字符替换为空字符的简单方法。如果您支持 C++11,所有这些都可以实现为 lambda,从而使代码更加简洁。
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char c[] = "Ch\0ad\0's Answ\0\0\0er.";
std::string data(c, c+19);
std::string c1;
struct is_null
{
bool operator()(const char c) const
{
return c == '\0';
}
};
// if you need to keep data_ intact (copy)
std::remove_copy_if(
data.begin(),
data.end(),
std::back_inserter(c1),
is_null());
std::cout << c1 << "\n";
// if you don't need to keep data intact, remove inline
std::string::iterator nend = std::remove_if(
data.begin(),
data.end(),
is_null());
data.erase(nend, data.end());
std::cout << data << "\n";
// simplest approach, just stream out each byte and skip the null characters
for(int x = 0; x < 19; ++x)
{
if(c[x] != '\0')
cout << c[x];
}
cout << "\n";
// If you want to decorate the null characters instead
std::string data2(c, c+19);
std::replace_if(
data2.begin(),
data2.end(),
is_null(),
'#'); // <--- this is the character that will replace the nulls
cout << data2 << "\n";
}