const char* concatenation

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

    In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:

    strcat(one,two); // append string two to string one.
    

    will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:

    char result[100];   // array to hold the result.
    
    strcpy(result,one); // copy string one into the result.
    strcat(result,two); // append string two to the result.
    
    0 讨论(0)
  • 2020-11-29 18:34

    The C way:

    char buf[100];
    strcpy(buf, one);
    strcat(buf, two);
    

    The C++ way:

    std::string buf(one);
    buf.append(two);
    

    The compile-time way:

    #define one "hello "
    #define two "world"
    #define concat(first, second) first second
    
    const char* buf = concat(one, two);
    
    0 讨论(0)
  • 2020-11-29 18:34

    If you don't know the size of the strings, you can do something like this:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(){
        const char* q1 = "First String";
        const char* q2 = " Second String";
    
        char * qq = (char*) malloc((strlen(q1)+ strlen(q2))*sizeof(char));
        strcpy(qq,q1);
        strcat(qq,q2);
    
        printf("%s\n",qq);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-29 18:36

    It seems like you're using C++ with a C library and therefore you need to work with const char *.

    I suggest wrapping those const char * into std::string:

    const char *a = "hello "; 
    const char *b = "world"; 
    std::string c = a; 
    std::string d = b; 
    cout << c + d;
    
    0 讨论(0)
  • 2020-11-29 18:40

    You can use strstream. It's formally deprecated, but it's still a great tool if you need to work with C strings, i think.

    char result[100]; // max size 100
    std::ostrstream s(result, sizeof result - 1);
    
    s << one << two << std::ends;
    result[99] = '\0';
    

    This will write one and then two into the stream, and append a terminating \0 using std::ends. In case both strings could end up writing exactly 99 characters - so no space would be left writing \0 - we write one manually at the last position.

    0 讨论(0)
  • 2020-11-29 18:45
    const char* one = "one";
    const char* two = "two";
    char result[40];
    sprintf(result, "%s%s", one, two);
    
    0 讨论(0)
提交回复
热议问题