我需要在c中加入"hello world".我怎样才能做到这一点 ?
string a = "hello ";
const char *b = "world";
const char *C;
Run Code Online (Sandbox Code Playgroud)
Gri*_*wes 30
string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();
Run Code Online (Sandbox Code Playgroud)
或不修改a:
string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();
Run Code Online (Sandbox Code Playgroud)
少量编辑,以匹配111111给出的信息量.
当你已经拥有strings(或const char *s,但我建议将后者转换为前者)时,你可以将它们"加"起来形成更长的字符串.但是,如果你想要附加的东西不仅仅是你已经拥有的字符串,你可以使用stringstream和它一样operator<<,它的工作方式完全一样cout,但不会将文本打印到标准输出(即控制台),而是它的内部缓冲区你可以用它的.str()方法来获取std::string它.
std::string::c_str()函数返回指向其中包含的字符串的const char缓冲区(即const char *)的指针,该字符串以空值终止.然后,您可以将其用作任何其他const char *变量.
如果你只需要连接然后使用operator +和operator +=函数
#include <string>
///...
std::string str="foo";
std::string str2=str+" bar";
str+="bar";
Run Code Online (Sandbox Code Playgroud)
但是,如果您有很多连接,那么您可以使用字符串流
#include <sstream>
//...
std::string str1="hello";
std::stringstream ss;
ss << str1 << "foo" << ' ' << "bar" << 1234;
std::string str=ss.str();
Run Code Online (Sandbox Code Playgroud)
编辑:然后您可以将字符串传递给C函数,并const char *使用c_str().
my_c_func(str1.c_str());
Run Code Online (Sandbox Code Playgroud)
如果C func采用非const char*或需要所有权,则可以执行以下操作
char *cp=std::malloc(str1.size()+1);
std::copy(str1.begin(), str2.end(), cp);
cp[str1.size()]='\0';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45365 次 |
| 最近记录: |