1

我在 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;
4

2 回答 2

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;
}
于 2010-06-27T08:22:04.987 回答
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;
}
于 2010-06-27T11:12:38.963 回答