题
我在c ++中有aa char数组,像{'a','b','c',0,0,0,0}
现在,我将其旋转到流中,我希望它看起来像“ ABC”,其中有四个空间,我主要使用std ::搅拌,而且我也有增强功能。我该如何在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;
解决方案
采用 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;
}
其他提示
如果您替换向量的数组,则另一种解决方案
#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;
}
不隶属于 StackOverflow