如何连接一个字符串和一个const char? [英] How concatenate a string and a const char?

查看:141
本文介绍了如何连接一个字符串和一个const char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要把hello world放在c。
我如何做到这一点?

  string a =hello 
const char * b =world;

const char * C;


解决方案

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

或不修改 a

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

稍微编辑,以匹配由 111111 p>

当你已经有 string s(或 const char * s,但我建议将后者转换为前者),你可以只是总和他们形成更长的字符串。但是,如果你想追加的东西不仅仅是你已经有的字符串,你可以使用 stringstream 和它的运算符<< ,它的工作原理是 cout 的一个,但不打印文本到标准输出(即控制台),而是它的内部缓冲区,你可以使用它 .str()方法从中获取 std :: string



std :: string :: c_str()函数返回 const char code> const char * ),它是以null结束的。然后可以使用它作为任何其他 const char * 变量。


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

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

const char *C;

解决方案

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

or without modifying 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.

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 stringstream and 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::string from it.

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

这篇关于如何连接一个字符串和一个const char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆