I need to concatenate two const chars like these:
const char *one = \"Hello \";
const char *two = \"World\";
How might I go about doing tha
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;
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);
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.
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?
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;