How to fill a section within c++ string?

℡╲_俬逩灬. 提交于 2021-02-18 11:13:28

问题


Having a string of whitespaces:

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

I'd like to fill length chars at a position.

In C it would look like

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

How can i achieve this with c++ string, I tried

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

but this seems to truncat the original string. Is there an easy C++ way to do this? Thanks.


回答1:


In addition to string::replace() you can use std::fill:

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

If you try to fill past the end of the string though, it will be ignored.




回答2:


First, to declare a simple string you don't need pointers:

std::string str;

To fill in a string with content of a given size, you can use the corresonding constructor:

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

To fill in strings you can use the replace method:

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

You must do convenient checks. You can also directly use iterators.

More generally for containers (string is a container of chars), you can also use the std::fill algorithm

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



回答3:


with one of replace(...) methods (documentation) you can do everything you need



来源:https://stackoverflow.com/questions/2891275/how-to-fill-a-section-within-c-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!