Anthoni Caldwell
Anthoni Caldwell

Reputation: 1545

const char* concatenation

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.

Upvotes: 151

Views: 343648

Answers (14)

vtopunov
vtopunov

Reputation: 1

std::string concat_cpp98(const char* left, const char* right)
{
    const size_t left_len = strlen(left);
    const size_t right_len = strlen(right);

    std::string result;
    result.reserve(left_len + right_len);
    result.append(left, left_len);
    result.append(right, right_len);
    return result;
}

std::string concat_cpp17(std::string_view left, std::string_view right)
{
    std::string result;
    result.reserve(left.size() + right.size());
    result.append(left);
    result.append(right);
    return result;
}

int main()
{
    const char* one = "Hello ";
    const char* two = "World";
    std::cout << concat_cpp98(one, two) << '\n'
              << concat_cpp17(one, two);

    return 0;
}

Upvotes: 0

carnicer
carnicer

Reputation: 523

There is a C-style trick for achieving the (const/constexpr) string literals concatenation in build time. It should not matter because const char* are actually C-style stuff anyhow. And without dynamic allocations, strlen, and all the ugly stuff posted here. Everything is done by the compiler, nothing during execution.

The trick is to use the preprecessor #define directive.

#define PREFIX "/dev/"
#define DEVICE PREFIX "pts/3"

constexpr const char* defaultDevice = DEVICE;

This should assign /dev/pts/3 to the variable (without any blank between the 2 preprocessor macros).

Upvotes: 0

Pedro Reis
Pedro Reis

Reputation: 1693

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

string total( string(one) + two );

// to use the concatenation as const char*, use:
total.c_str()

Updated: 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)

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

Upvotes: 23

Anoroah
Anoroah

Reputation: 2119

If you don't know the size of the strings, you can do something like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    const char* q1 = "First String";
    const char* q2 = " Second String";

    char * qq = (char*) malloc((strlen(q1)+ strlen(q2))*sizeof(char));
    strcpy(qq,q1);
    strcat(qq,q2);

    printf("%s\n",qq);

    return 0;
}

Upvotes: 5

Edin Jašarević
Edin Jašarević

Reputation: 1

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;

Upvotes: 0

Prasoon Saurav
Prasoon Saurav

Reputation: 92924

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()

Upvotes: 34

codaddict
codaddict

Reputation: 455400

In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:

strcat(one,two); // append string two to string one.

will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:

char result[100];   // array to hold the result.

strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.

Upvotes: 136

Gregory Pakosz
Gregory Pakosz

Reputation: 70254

Using std::string:

#include <string>

std::string result = std::string(one) + std::string(two);

Upvotes: 27

Paul Tomblin
Paul Tomblin

Reputation: 182880

First of all, you have to create some dynamic memory space. Then you can just strcat the two strings into it. Or you can use the c++ "string" class. The old-school C way:

  char* catString = malloc(strlen(one)+strlen(two)+1);
  strcpy(catString, one);
  strcat(catString, two);
  // use the string then delete it when you're done.
  free(catString);

New C++ way

  std::string three(one);
  three += two;

Upvotes: 5

Jagannath
Jagannath

Reputation: 4025

const char* one = "one";
const char* two = "two";
char result[40];
sprintf(result, "%s%s", one, two);

Upvotes: 3

Luca Matteis
Luca Matteis

Reputation: 29267

It seems like you're using C++ with a C library and therefore you need to work with const char *.

I suggest wrapping those const char * into std::string:

const char *a = "hello "; 
const char *b = "world"; 
std::string c = a; 
std::string d = b; 
cout << c + d;

Upvotes: 5

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507363

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.

Upvotes: 3

One more example:

// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(one) + strlen(two) + 1;

// allocate enough memory for the concatenated string:
char* concatString = new char[ bufferSize ];

// copy strings one and two over to the new buffer:
strcpy( concatString, one );
strcat( concatString, two );

...

// delete buffer:
delete[] concatString;

But unless you specifically don't want or can't use the C++ standard library, using std::string is probably safer.

Upvotes: 10

Idan K
Idan K

Reputation: 20901

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);

Upvotes: 97

Related Questions