C++ 如何连接字符串和常量字符?

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

How concatenate a string and a const char?

c++string

提问by xRobot

I need to put "hello world" in c. How can I do this ?

我需要将“hello world”放在 c 中。我怎样才能做到这一点 ?

string a = "hello ";
const char *b = "world";

const char *C;

回答by Griwes

string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();

or without modifying a:

或不修改a

string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();

Little edit, to match amount of information given by 111111.

小编辑,以匹配111111 提供的信息量。

When you already have strings (or const char *s, but I recommend casting the latter to the former), you can just "sum" them up to form longer string. But, if you want to append something more than just string you already have, you can use stringstreamand it's operator<<, which works exactly as cout's one, but doesn't print the text to standard output (i.e. console), but to it's internal buffer and you can use it's .str()method to get std::stringfrom it.

当您已经有strings (或const char *s,但我建议将后者转换为前者)时,您可以将它们“求和”以形成更长的字符串。但是,如果您想附加的不仅仅是您已经拥有的字符串,您可以使用stringstreamand it's operator<<,它的工作原理与cout's one完全一样,但不会将文本打印到标准输出(即控制台),而是打印到它的内部缓冲区你可以使用它的.str()方法从中获取std::string

std::string::c_str()function returns pointer to const charbuffer (i.e. const char *) of string contained within it, that is null-terminated. You can then use it as any other const char *variable.

std::string::c_str()函数返回指向const char缓冲区(即const char *)中包含的字符串的指针,即以空字符结尾。然后您可以将其用作任何其他const char *变量。

回答by 111111

if you just need to concatenate then use the operator +and operator +=functions

如果您只需要连接,则使用operator +operator +=函数

 #include <string>
 ///...
 std::string str="foo";
 std::string str2=str+" bar";
 str+="bar";

However if you have a lot of conacatenation to do then you can use a string stream

但是,如果您有很多连接要做,那么您可以使用字符串流

#include <sstream>
//...
std::string str1="hello";
std::stringstream ss;
ss << str1 << "foo" << ' ' << "bar" << 1234;
std::string str=ss.str();

EDIT: you can then pass the string to a C function taking a const char *with c_str().

编辑:然后您可以将字符串传递给const char *带有 with的 C 函数c_str()

my_c_func(str1.c_str());

and If the C func takes a non const char * or require ownership you can do the following

如果 C func 采用非 const char * 或需要所有权,您可以执行以下操作

char *cp=std::malloc(str1.size()+1);
std::copy(str1.begin(), str2.end(), cp);
cp[str1.size()]='##代码##';