本文介绍了最优雅的方式来初始化一个字符串与一个字符从另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更优雅的方式来初始化第一个字符串的单个字符串的第二个字符串?例如。而不使用字符串(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]};更多推荐
最优雅的方式来初始化一个字符串与一个字符从另一个字符串
发布评论