如何在一行上连接多个 C++ 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/662918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I concatenate multiple C++ strings on one line?
提问by Nick Bolton
C# has a syntax feature where you can concatenate many data types together on 1 line.
C# 具有语法功能,您可以在其中将许多数据类型连接到 1 行。
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
What would be the equivalent in C++? As far as I can see, you'd have to do it all on separate lines as it doesn't support multiple strings/variables with the + operator. This is OK, but doesn't look as neat.
C++ 中的等价物是什么?据我所知,您必须在单独的行上完成所有操作,因为它不支持使用 + 运算符的多个字符串/变量。这很好,但看起来不那么整洁。
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.
上面的代码产生一个错误。
回答by Paolo Tedesco
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm
看看 Herb Sutter 的这篇本周大师文章:庄园农场的字符串格式化程序
回答by Michel
In 5 years nobody has mentioned .append
?
5年没人提过.append
?
#include <string>
std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
回答by Michel
s += "Hello world, " + "nice to see you, " + "or not.";
Those character array literals are not C++ std::strings - you need to convert them:
这些字符数组文字不是 C++ std::strings - 您需要转换它们:
s += string("Hello world, ") + string("nice to see you, ") + string("or not.");
To convert ints (or any other streamable type) you can use a boost lexical_cast or provide your own function:
要转换整数(或任何其他可流式传输类型),您可以使用 boost lexical_cast 或提供您自己的函数:
template <typename T>
string Str( const T & t ) {
ostringstream os;
os << t;
return os.str();
}
You can now say things like:
你现在可以这样说:
string s = string("The meaning is ") + Str( 42 );
回答by John Dibling
Your code can be written as1,
你的代码可以写成1,
s = "Hello world," "nice to see you," "or not."
...but I doubt that's what you're looking for. In your case, you are probably looking for streams:
......但我怀疑这就是你要找的。在您的情况下,您可能正在寻找流:
std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
1"can be written as" : This only works for string literals. The concatenation is done by the compiler.
1"可以写成" :这仅适用于字符串文字。连接由编译器完成。
回答by Rapptz
Using C++14 user defined literals and std::to_string
the code becomes easier.
使用 C++14 用户定义文字,std::to_string
代码变得更容易。
using namespace std::literals::string_literals;
std::string str;
str += "Hello World, "s + "nice to see you, "s + "or not"s;
str += "Hello World, "s + std::to_string(my_int) + other_string;
Note that concatenating string literals can be done at compile time. Just remove the +
.
请注意,连接字符串文字可以在编译时完成。只需删除+
.
str += "Hello World, " "nice to see you, " "or not";
回答by SebastianK
To offer a solution that is more one-line-ish: A function concat
can be implemented to reduce the "classic" stringstream based solution to a single statement.
It is based on variadic templates and perfect forwarding.
提供一种更单行的解决方案:concat
可以实现一个函数以将基于“经典”字符串流的解决方案简化为单个语句。它基于可变参数模板和完美转发。
Usage:
用法:
std::string s = concat(someObject, " Hello, ", 42, " I concatenate", anyStreamableType);
Implementation:
执行:
void addToStream(std::ostringstream&)
{
}
template<typename T, typename... Args>
void addToStream(std::ostringstream& a_stream, T&& a_value, Args&&... a_args)
{
a_stream << std::forward<T>(a_value);
addToStream(a_stream, std::forward<Args>(a_args)...);
}
template<typename... Args>
std::string concat(Args&&... a_args)
{
std::ostringstream s;
addToStream(s, std::forward<Args>(a_args)...);
return s.str();
}
回答by vitaut
In C++20 you'll be able to do:
在 C++20 中,您将能够执行以下操作:
auto s = std::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Until then you could do the same with the {fmt} library:
在此之前,您可以对{fmt} 库执行相同操作:
auto s = fmt::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Disclaimer: I'm the author of {fmt}.
免责声明:我是 {fmt} 的作者。
回答by bayda
boost::format
提升::格式
or std::stringstream
或 std::stringstream
std::stringstream msg;
msg << "Hello world, " << myInt << niceToSeeYouString;
msg.str(); // returns std::string object
回答by Wolf
The actual problemwas that concatenating string literals with +
fails in C++:
在实际的问题是,串联字符串常量与+
在C ++中失败:
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
上面的代码产生一个错误。
In C++ (also in C), you concatenate string literals by just placing them right next to each other:
在 C++ 中(也在 C 中),您只需将字符串文字并排放置即可连接它们:
string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 =
"Hello world, " /*line breaks in source code as well as*/
"nice to see you, " /*comments don't matter*/
"or not.";
This makes sense, if you generate code in macros:
这是有道理的,如果您在宏中生成代码:
#define TRACE(arg) cout << #arg ":" << (arg) << endl;
...a simple macro that can be used like this
...一个可以像这样使用的简单宏
int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)
(现场演示...)
or, if you insist in using the +
for string literals (as already suggested by underscore_d):
或者,如果您坚持使用+
for 字符串文字(正如underscore_d已经建议的那样):
string s = string("Hello world, ")+"nice to see you, "+"or not.";
Another solution combines a string and a const char*
for each concatenation step
另一种解决方案const char*
为每个连接步骤组合了一个字符串和一个
string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
回答by Shital Shah
auto s = string("one").append("two").append("three")