我在C ++中有一个char数组,它类似于{'a','b','c',0,0,0,0}
现在将它改为流,我希望它看起来像“abc”,其中有四个空格。 我主要使用std :: stiring,我也有提升。 我怎么能在C ++中做到这一点
基本上我认为我正在寻找像
这样的东西char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually...
std::string newString(hellishCString, sizeof(hellishCString));
newString.Replace(0,' '); // not real C++
ar << newString;
答案 0 :(得分:10)
使用std::replace
:
#include <string>
#include <algorithm>
#include <iostream>
int main(void) {
char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually...
std::string newString(hellishCString, sizeof hellishCString);
std::replace(newString.begin(), newString.end(), '\0', ' ');
std::cout << '+' << newString << '+' << std::endl;
}
答案 1 :(得分:1)
如果用向量
替换数组,还有一个解决方案#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
char replaceZero(char n)
{
return (n == 0) ? ' ' : n;
}
int main(int argc, char** argv)
{
char hellish[] = {'a','b','c',0,0,0,0};
std::vector<char> hellishCString(hellish, hellish + sizeof(hellish));
std::transform(hellishCString.begin(), hellishCString.end(), hellishCString.begin(), replaceZero);
std::string result(hellishCString.begin(), hellishCString.end());
std::cout << result;
return 0;
}