有一串空格:
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++ 方法可以做到这一点? 谢谢。
最佳答案
除了 string::replace()
之外,您还可以使用 std::fill
:
std::fill(str->begin()+pos, str->begin()+pos+length, '#');
//or:
std::fill_n(str->begin()+pos, length, '#');
如果您尝试填充超过字符串末尾的内容,它将被忽略。
关于c++ - 如何在 C++ 字符串中填充一个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2891275/