Question

I am new to c++ and am looking for a way to concatenate three char* strings together ? Can anyone show me some sample code ?

Kind Regards,

Was it helpful?

Solution

In C++ you typically use std::string for strings. With that you can concatenate with the + operator. For instance:

std::string s = s1 + s2 + s3;

where s1, s2 and s3 are your three strings held in std::string variables.

If you have s1, s2 and s3 as char* or const char* then you write it a little differently.

std::string s = s1; // calls const char* constructor
s += s2; // calls operator+=() overload that accepts const char*
s += s3; // and again

If you really want to use null-terminated C strings, and C string functions, then you use strcpy to copy and strcat to concatenate.

char[SOME_LARGE_ENOUGH_VALUE] str;
strcpy(str, s1);
strcat(str, s2);
strcat(str, s3);

where s1, s2 and s3 are your three strings as char* or const char*.

Of course, choosing SOME_LARGE_ENOUGH_VALUE is the fun part. If this is a learning exercise, then you might like to learn how to allocate the string dynamically.

char *str = new char[strlen(s1) + strlen(s2) + strlen(s3) + 1];

Then you can use the strcpy, strcat shuffle above. But now you are responsible for destroying the raw memory that you allocated. So, think about how to do that in a robust way, and then use std::string!


From the comments, it seems you want to concatenate three strings, and then pass the resulting string to a low-level hash function that accepts a C string. So, I suggest that you do all your work with std::string. Only at the last minute, when you call the hash function, use the c_str() function to get a const char* representation of the concatenated string.

OTHER TIPS

const char * foo = "foo";
const char * bar = "bar";
const char * baz = "baz";

One option:

std::string s = foo;
s += bar;
s += baz;

Another option:

std::stringstream ss;
ss << foo << bar << baz;
std::string s = ss.str();

Another option of last resort:

char* s = new char [strlen (foo) + strlen (bar) + strlen (baz) + 1];
s[0] = 0;
strcat (s, foo);
strcat (s, bar);
strcat (s, baz);
// ...
delete [] s;
std::string s1( "Hello " );
std::string s2( "C++ " );
std::string s3( "amateur" );

s1 += s2 + s3;

std::cout << s1 << std::endl; 

Or

char s1[18] = "Hello ";
char s2[] =  "C++ ";
char s3[] = "amateur";

std::strcat( std::strcat( s1, s2 ), s3 );

std::cout << s1 << std::endl; 

A simple way to concatenate:

 #include <iostream>

int main()
{
    const char* a = "welcome ";
    const char* b = "to C++ ";
    const char* c = "world";
    std::string d(a);
    std::cout<< d.append(b).append(c);

   return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top