Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a section within c++ string?

Tags:

c++

c

string

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.

like image 749
stacker Avatar asked May 23 '10 09:05

stacker


People also ask

Can you edit strings in C?

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).

How do you get a section of a string in C++?

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.

Is it possible to modify a string literal?

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.


2 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 past the end of the string though, it will be ignored.

like image 57
gnud Avatar answered Oct 14 '22 13:10

gnud


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, '#' );
like image 28
Nikko Avatar answered Oct 14 '22 14:10

Nikko