【问题标题】:C++ looking for String.Replace()C++ 寻找 String.Replace()
【发布时间】:2010-06-27 08:14:37
【问题描述】:

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

【问题讨论】:

  • std::string 可以包含嵌入的空字符吗?另一种选择可能是改用std::vector
  • @dreamlax:是的,他们可以。字符串的长度是独立存储的,因此不需要空终止,空字符也不会被特殊处理。

标签: c++ stdstring


【解决方案1】:

使用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;
}

【讨论】:

  • 错误 7 错误 C2782: 'void std::replace(_FwdIt,_FwdIt,const _Ty &,const _Ty &)' : 模板参数 '_Ty' 不明确
  • 我的错误,我试过:std::replace(groupString.begin(), groupString.end(), 0, ' ');而 0 显然是 int...
【解决方案2】:

如果用向量替换数组,还有一个解决方案

#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;
}

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2011-11-04
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多