views:

122

answers:

4

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.

A: 

Exactly the same in C++

Martin York
@Martin York could you please give an example? Should I use str->c_str() for memset?
stacker
@stacker `memset(` works in C++, if the string conforms to the appropriate version of the standard requiring contiguous storage. But it isn't very idiomatic.
Pete Kirkham
@stacker if you use `c_str()` it will _not_ work. You should not write to the buffer returned by `c_str()`.
gnud
+1  A: 

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

bobah
+2  A: 

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, '#' );
Nikko
stacker
yes, I had forgotten one argument but it's ok now
Nikko
+1 works also fine thanks.
stacker
+4  A: 

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.

gnud