初始化一个字符串后,是否可以在同一行中添加一个 char 和一个 char*:
char mod;//this comes in as a parameter
string line = "text";
line += mod;
line += "more text";
有没有更有效和/或可能的单线方式来做到这一点?就像是
string line = "text" + mod + "more text";
初始化一个字符串后,是否可以在同一行中添加一个 char 和一个 char*:
char mod;//this comes in as a parameter
string line = "text";
line += mod;
line += "more text";
有没有更有效和/或可能的单线方式来做到这一点?就像是
string line = "text" + mod + "more text";
你的单行代码不起作用,因为char *s 不是字符串,所以你不能用来+将它们与chars 连接;你最终会得到一个指针添加。如果你想要一个单线,你可以使用
string line = string("text") + mod + "more text";
但这不会比你的 3 行更有效。
你可以做你的第一个片段(你会发现它只是通过编译!),但不是你的第二个。
您还可以考虑使用std::stringstream:
std::stringstream ss;
ss << "text" << mod << "more text";
您只需要确保的第一个操作数+是 a std::string:
string line = string("text") + mod + "more text";
然后结果string("text") + mod是 astd::string并且也可以"more text"附加到它上面。
运算符+=返回一个非常量引用,因此您可以stack +=。这有点尴尬和不寻常,看起来像这样:
string line = "text";
(line += mod) += "more text";