如何在c ++字符串中填充一节?

sta*_*ker 7 c c++ string

有一串空格:

string *str = new string();
str->resize(width,' ');
Run Code Online (Sandbox Code Playgroud)

我想在一个位置填充长度字符.

在C中它看起来像

memset(&str[pos],'#', length );
Run Code Online (Sandbox Code Playgroud)

我怎么能用c ++字符串实现这一点,我试过了

 string& assign( const string& str, size_type index, size_type len );
Run Code Online (Sandbox Code Playgroud)

但这似乎截断了原始字符串.有一种简单的C++方法吗?谢谢.

gnu*_*nud 10

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

std::fill(str->begin()+pos, str->begin()+pos+length, '#');
//or:
std::fill_n(str->begin()+pos, length, '#');
Run Code Online (Sandbox Code Playgroud)

如果您尝试填充字符串的末尾,则会被忽略.


Nik*_*kko 7

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

std::string str;
Run Code Online (Sandbox Code Playgroud)

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

std::string str( width, ' ' );
Run Code Online (Sandbox Code Playgroud)

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

 str.replace( pos, length, length , '#' );
Run Code Online (Sandbox Code Playgroud)

你必须做方便的检查.您也可以直接使用迭代器.

更常见的是容器(字符串是字符的容器),您也可以使用std :: fill算法

std::fill( str.begin()+pos, str.begin()+pos+length, '#' );
Run Code Online (Sandbox Code Playgroud)