Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char* concatenation

People also ask

Can char * be concatenated?

The strcat() function takes char array as input and then concatenates the input values passed to the function.

How do you add two const characters?

"const" means "cannot be changed(*1)". So you cannot simply "add" one const char string to another (*2). What you can do is copy them into a non-const character buffer. const char* a = ...; const char* b = ...; char buffer[256]; // <- danger, only storage for 256 characters.

What does const char * const mean?

const char * const Constant pointer (pointer can't be changed) to constant data (data cannot be modified).

What is concatenation in C++?

Concatenation of two strings is the joining of them to form a new string. For example. String 1: Mangoes are String 2: tasty Concatenation of 2 strings: Mangoes are tasty. A program to concatenate two strings is given as follows.


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.

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

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


Using std::string:

#include <string>

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

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?