C++ 如何将多个字符组合成一个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20449590/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:08:48  来源:igfitidea点击:

How can I combine multiple char's to make a string?

c++stringchar

提问by Sarah

I am doing string parsing and essentially what I would like to do is something like this:

我正在做字符串解析,基本上我想做的是这样的:

string signature = char[index+1] + '/' + char[index+2];

BUT you can't do string concatenation on char's so that brings me to this question, how can I simulate concatenation on char's?

但是你不能在 char 上进行字符串连接,这让我想到了这个问题,我如何模拟 char 上的连接?

I know that the string library in C++ has append but I don't think that works for my case. Any ideas?

我知道 C++ 中的字符串库有 append 但我认为这不适用于我的情况。有任何想法吗?

回答by Benjamin Lindley

You can concatenate chars to a std::string, you just need one of the operands to be a std::string, otherwise you are adding integers.

您可以将字符连接到 a std::string,您只需要其中一个操作数是 a std::string,否则您将添加整数。

std::string signature = std::string() + char_array[index+1] + '/' + char_array[index+2];

Note that this only works if either the first or second operand in the chain is a std::string. That will result in the first call to operator+returning a std::string, and the rest will follow suit. So this doesn't give the expected results:

请注意,这仅在链中的第一个或第二个操作数是 a 时才有效std::string。这将导致第一次调用operator+返回 a std::string,其余的将效仿。所以这并没有给出预期的结果:

std::string signature = char_array[index+1] + '/' + char_array[index+2] + std::string();

回答by Steve Jessop

In C++11 you can actually do:

在 C++11 中,您实际上可以执行以下操作:

std::string signature{chars[index+1], '/', chars[index+2]};

Not sure how useful this will be in real code, but it deals with your example.

不确定这在实际代码中会有多大用处,但它处理您的示例。

回答by Zac Howland

In addition to Steve's and Benjamin's solution, you can also use a std::stringstream:

除了史蒂夫和本杰明的解决方案,您还可以使用std::stringstream

std::stringstream ss;
ss << char_array[index + 1] << '/' << char_array[index + 2];
std::string s = ss.str();

回答by Joe Z

You can concatenate characters and C-style strings to an existing string rather easily:

您可以很容易地将字符和 C 样式字符串连接到现有字符串:

string signature;

signature += char_array[index + 1];  // append character from char_array[index+1]
signature += '/';
signature += char_array[index + 2];  // append character from char_array[index+2]

You just need to ensure the left side of the +or +=is a std::string.

您只需要确保+or的左侧+=std::string.

回答by Carth

If you were doing this with .Net a character array can be used in the string constructor.

如果您使用 .Net 执行此操作,则可以在字符串构造函数中使用字符数组。

http://msdn.microsoft.com/en-us/library/ttyxaek9(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/ttyxaek9(v=vs.110).aspx