简体   繁体   中英

Most elegant way to initialise a string with a single character from another string

Is there a more elegant way to initialise the second string with a single char from the first string? Eg. without resorting to the string ( size_t n, char c ) constructor?

string first = "foobar";
string second(string(1, first[0]));

The constructor you mention is the way to create a string from one character, so there won't be a significantly more elegant way. However, there's no need to create and copy/move a temporary:

string second(1, first[0]);

Alternatively, you could construct from a substring of first :

string second(first, 0, 1);

In C++11, you can use an initialiser list:

string second {first[0]};

What about:

string ( );
string ( const string& str );
string ( const string& str, size_t pos, size_t n = npos );
string ( const char * s, size_t n );
string ( const char * s );
string ( size_t n, char c ); //<<--- this

ie

string second(1, first[0]);

Note that the above are your only options for initialization.

I suggest you:

string first = "foobar";
string second;
second = first[0];

Is there a more elegant way to initialise the second string with a single char from the first string? Eg. without resorting to the string ( size_t n, char c ) constructor?

string first = "foobar";
string second(string(1, first[0]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM