如何在一行上连接多个C++字符串?

Nic*_*ton 136 c++ string compiler-errors concatenation

C#具有语法功能,您可以在一行中将多种数据类型连接在一起.

string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
Run Code Online (Sandbox Code Playgroud)

什么是C++中的等价物?据我所知,你必须在单独的行上完成所有操作,因为它不支持使用+运算符的多个字符串/变量.这没关系,但看起来并不整洁.

string s;
s += "Hello world, " + "nice to see you, " + "or not.";
Run Code Online (Sandbox Code Playgroud)

上面的代码产生错误.

Pao*_*sco 226

#include <sstream>
#include <string>

std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
Run Code Online (Sandbox Code Playgroud)

看看Herb Sutter撰写的本周大师文章:Manor Farm的String Formatters

  • ss <<"哇,C++中的字符串连接是令人印象深刻的"<<或者不是." (35认同)
  • 试试这个:`std :: string s = static_cast <std :: ostringstream&>(std :: ostringstream().seekp(0)<<"HelloWorld"<< myInt << niceToSeeYouString).str();` (5认同)
  • 只是说另一种方式:使用多个追加:string s = string(“ abc”)。append(“ def”)。append(otherStrVar).append(to_string(123)); (3认同)
  • 但是..这是3行 (2认同)

Mic*_*hel 63

5年没有人提到过.append

#include <string>

std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
Run Code Online (Sandbox Code Playgroud)

  • @Jonny`s.append("One").append("expression");`也许我应该编辑原文以这种方式使用返回值? (14认同)
  • `s.append( "一"); s.append("line");` (7认同)
  • @SilverMölsOP在等效的C#代码和非编译C++代码中的另一行声明`s`.他想要的C++是`s + ="Hello world,"+"很高兴见到你",+"或不是.";``这可以写成`s.append("Hello world,").append("很高兴见到你,").支持("或不.");` (4认同)
  • `append`的一个主要优点是它在字符串包含NUL字符时也有效. (4认同)

小智 59

s += "Hello world, " + "nice to see you, " + "or not.";
Run Code Online (Sandbox Code Playgroud)

那些字符数组文字不是C++ std :: strings - 你需要转换它们:

s += string("Hello world, ") + string("nice to see you, ") + string("or not.");
Run Code Online (Sandbox Code Playgroud)

要转换int(或任何其他可流式类型),您可以使用boost lexical_cast或提供自己的函数:

template <typename T>
string Str( const T & t ) {
   ostringstream os;
   os << t;
   return os.str();
}
Run Code Online (Sandbox Code Playgroud)

你现在可以这样说:

string s = "The meaning is " + Str( 42 );
Run Code Online (Sandbox Code Playgroud)

  • 你只需要显式转换第一个:s + = string("Hello world,")+"很高兴见到你","+或不."; (15认同)
  • 是的,但我无法解释为什么! (8认同)
  • 在构造函数string(“ Hello world”)右侧进行的连接是通过在string类中定义的operator +()执行的。如果表达式中没有“ string”对象,则串联仅是char指针“ char *”的总和。 (2认同)

Joh*_*ing 40

您的代码可以写成1,

s = "Hello world," "nice to see you," "or not."
Run Code Online (Sandbox Code Playgroud)

...但我怀疑这就是你要找的东西.在您的情况下,您可能正在寻找流:

std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
Run Code Online (Sandbox Code Playgroud)

1 " 可写为 ":这仅适用于字符串文字.连接由编译器完成.

  • 你的第一个例子值得一提,但也请注意它只适用于"连接"文字字符串(编译器本身会执行连接). (10认同)

Rap*_*ptz 24

使用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;
Run Code Online (Sandbox Code Playgroud)

请注意,可以在编译时完成串联字符串文字.只需删除+.

str += "Hello World, " "nice to see you, " "or not";
Run Code Online (Sandbox Code Playgroud)

  • 从C++ 11开始,您可以使用std :: to_string (2认同)

Seb*_*anK 16

提供更一行的解决方案:concat可以实现一种功能,将基于"经典"字符串流的解决方案简化为单一语句.它基于可变参数模板和完美转发.


用法:

std::string s = concat(someObject, " Hello, ", 42, " I concatenate", anyStreamableType);
Run Code Online (Sandbox Code Playgroud)

执行:

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();
}
Run Code Online (Sandbox Code Playgroud)


bay*_*yda 7

提高::格式

或者std :: stringstream

std::stringstream msg;
msg << "Hello world, " << myInt  << niceToSeeYouString;
msg.str(); // returns std::string object
Run Code Online (Sandbox Code Playgroud)


Wol*_*olf 6

实际的问题是,串联字符串常量与+在C++中失败:

string s;
s += "Hello world, " + "nice to see you, " + "or not.";
上面的代码产生错误.

在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.";
Run Code Online (Sandbox Code Playgroud)

如果您在宏中生成代码,这是有道理的:

#define TRACE(arg) cout << #arg ":" << (arg) << endl;
Run Code Online (Sandbox Code Playgroud)

...一个可以像这样使用的简单宏

int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)
Run Code Online (Sandbox Code Playgroud)

(现场演示......)

或者,如果你坚持使用+for字符串文字(正如underscore_d已经建议的那样):

string s = string("Hello world, ")+"nice to see you, "+"or not.";
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是const char*为每个连接步骤组合一个字符串和一个

string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
Run Code Online (Sandbox Code Playgroud)


Shi*_*hah 5

auto s = string("one").append("two").append("three")
Run Code Online (Sandbox Code Playgroud)


vit*_*aut 5

使用{fmt}库,您可以执行以下操作:

auto s = fmt::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Run Code Online (Sandbox Code Playgroud)

建议将该库的子集标准化为P0645文本格式,如果被接受,则以上内容将变为:

auto s = std::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Run Code Online (Sandbox Code Playgroud)

免责声明:我是{fmt}库的作者。