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.
The only difference is that you cannot modify string literals, whereas you can modify arrays. Functions that take a C-style string will be just as happy to accept string literals unless they modify the string (in which case your program will crash).
A function to obtain a substring in C++ is substr(). This function contains two parameters: pos and len. The pos parameter specifies the start position of the substring and len denotes the number of characters in a substring.
C Language Undefined behavior Modify string literalAttempting to modify the string literal has undefined behavior. However, modifying a mutable array of char directly, or through a pointer is naturally not undefined behavior, even if its initializer is a literal string.
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.
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, '#' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With