const char* concatenation

前端 未结 12 2135
抹茶落季
抹茶落季 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:22

    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;
    
    0 讨论(0)
  • 2020-11-29 18:24

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

    0 讨论(0)
  • 2020-11-29 18:25

    Using std::string:

    #include <string>
    
    std::string result = std::string(one) + std::string(two);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 18:30
    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?
    
    0 讨论(0)
  • 2020-11-29 18:30

    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;
    
    0 讨论(0)
提交回复
热议问题