Search code examples
c++stringc-stringsstring-concatenation

C++ concat three char* strings togther


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,


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.