const char* concatenation

2019-01-10 07:00发布

I need to concatenate two const chars like these:

const char *one = "Hello ";
const char *two = "World";

How might I go about doing that?

I am passed these char*s from a third-party library with a C interface so I can't simply use std::string instead.

12条回答
手持菜刀,她持情操
2楼-- · 2019-01-10 07:18
const char* one = "one";
const char* two = "two";
char result[40];
sprintf(result, "%s%s", one, two);
查看更多
迷人小祖宗
3楼-- · 2019-01-10 07:20

If you are using C++, why don't you use std::string instead of C-style strings?

std::string one="Hello";
std::string two="World";

std::string three= one+two;

If you need to pass this string to a C-function, simply pass three.c_str()

查看更多
乱世女痞
4楼-- · 2019-01-10 07:22

The C way:

char buf[100];
strcpy(buf, one);
strcat(buf, two);

The C++ way:

std::string buf(one);
buf.append(two);

The compile-time way:

#define one "hello "
#define two "world"
#define concat(first, second) first second

const char* buf = concat(one, two);
查看更多
孤傲高冷的网名
5楼-- · 2019-01-10 07:22

You can use strstream. It's formally deprecated, but it's still a great tool if you need to work with C strings, i think.

char result[100]; // max size 100
std::ostrstream s(result, sizeof result - 1);

s << one << two << std::ends;
result[99] = '\0';

This will write one and then two into the stream, and append a terminating \0 using std::ends. In case both strings could end up writing exactly 99 characters - so no space would be left writing \0 - we write one manually at the last position.

查看更多
Viruses.
6楼-- · 2019-01-10 07:27

Update: changed string total = string(one) + string(two); to string total( string(one) + two ); for performance reasons (avoids construction of string two and temporary string total)

const char *one = "Hello ";
const char *two = "World";

string total( string(one) + two );    // OR: string total = string(one) + string(two);
// string total(move(move(string(one)) + two));  // even faster?

// to use the concatenation in const char* use
total.c_str()
查看更多
Animai°情兽
7楼-- · 2019-01-10 07:29

Connecting two constant char pointer without using strcpy command in the dynamic allocation of memory:

const char* one = "Hello ";
const char* two = "World!";

char* three = new char[strlen(one) + strlen(two) + 1] {'\0'};

strcat_s(three, strlen(one) + 1, one);
strcat_s(three, strlen(one) + strlen(two) + 1, two);

cout << three << endl;

delete[] three;
three = nullptr;
查看更多
登录 后发表回答