【问题标题】:How to fill a section within c++ string?如何在 C++ 字符串中填充一个部分?
【发布时间】:2010-05-23 09:53:46
【问题描述】:

有一串空格:

string *str = new string();
str->resize(width,' ');

我愿意 在某个位置填充长度字符。

在 C 中看起来像

memset(&str[pos],'#', length );

我如何用 c++ 字符串实现这一点,我试过了

 string& assign( const string& str, size_type index, size_type len );

但这似乎截断了原始字符串。 有没有一种简单的 C++ 方法可以做到这一点? 谢谢。

【问题讨论】:

  • 是否有理由在您的示例中动态分配字符串?
  • @GMan - 我不希望它们作为自动变量,而是以邪恶的 strdup() 方式在堆上

标签: c++ c string


【解决方案1】:

除了string::replace(),你还可以使用std::fill

std::fill(str->begin()+pos, str->begin()+pos+length, '#');
//or:
std::fill_n(str->begin()+pos, length, '#');

如果您尝试填充超过字符串的末尾,它将被忽略。

【讨论】:

    【解决方案2】:

    首先,声明一个不需要指针的简单字符串:

    std::string str;
    

    要使用给定大小的内容填充字符串,可以使用相应的构造函数:

    std::string str( width, ' ' );
    

    要填写字符串可以使用replace方法:

     str.replace( pos, length, length , '#' );
    

    您必须进行方便的检查。您也可以直接使用迭代器。

    更一般地用于容器(字符串是字符的容器),您也可以使用 std::fill 算法

    std::fill( str.begin()+pos, str.begin()+pos+length, '#' );
    

    【讨论】:

    • 编译器仍然抱怨 - 有什么建议吗?错误:来自char' to const char*' 的无效转换错误:初始化`std::basic_string<_chart _traits _alloc>& std::basic_string<_chart _traits _alloc>::replace(typename _Alloc:: size_type, typename _Alloc::size_type, const _CharT*) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]'
    【解决方案3】:

    使用 replace(...) 方法之一 (documentation),您可以做任何您需要的事情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多