const char* concatenation

前端 未结 12 2170
抹茶落季
抹茶落季 2020-11-29 18:09

I need to concatenate two const chars like these:

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

How might I go about doing tha

12条回答
  •  情深已故
    2020-11-29 18:28

    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.

提交回复
热议问题