How to fill a section in a C ++ line?

The presence of a string of spaces:

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

I would like to enter the length characters in the position.

In C, it will look like

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

How can I achieve this with a C ++ line, I tried

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

but this seems to truncate the original string. Is there a simple C ++ way to do this? Thanks.

+6
c ++ c string
source share
3 answers

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 in the last end of the line, it will be ignored.

+9
source share

First, to declare a simple string, you do not need pointers:

 std::string str; 

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

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

To fill in the lines, you can use the replace method:

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

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

In general, for containers (a string is a container of characters), you can also use the std :: fill algorithm

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

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

+1
source share

All Articles