问题
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