最优雅的方式来初始化一个字符串与一个字符从另一个字符串

编程入门 行业动态 更新时间:2024-10-27 10:25:17
本文介绍了最优雅的方式来初始化一个字符串与一个字符从另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有更优雅的方式来初始化第一个字符串的单个字符串的第二个字符串?例如。而不使用字符串(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]};

更多推荐

最优雅的方式来初始化一个字符串与一个字符从另一个字符串

本文发布于:2023-11-06 21:56:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564781.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   初始化   字符   优雅   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!