最优雅的方式来初始化一个字符串与一个字符从另一个字符串 [英] Most elegant way to initialise a string with a single character from another string

查看:307
本文介绍了最优雅的方式来初始化一个字符串与一个字符从另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更优雅的方式来初始化第一个字符串的单个字符串的第二个字符串?例如。而不使用字符串(size_t n,char c)构造函数?

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]);

或者,您可以从的子字符串

string second(first, 0, 1);

在C ++ 11中,可以使用初始化列表:

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

string second {first[0]};

这篇关于最优雅的方式来初始化一个字符串与一个字符从另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆