How do I concatenate const/literal strings in C?

前端 未结 17 1803
醉梦人生
醉梦人生 2020-11-21 23:45

I\'m working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat(\"TEXT \", var);

message2 = strcat(strcat(\"TEXT          


        
17条回答
  •  深忆病人
    2020-11-22 00:13

    You can write your own function that does the same thing as strcat() but that doesn't change anything:

    #define MAX_STRING_LENGTH 1000
    char *strcat_const(const char *str1,const char *str2){
        static char buffer[MAX_STRING_LENGTH];
        strncpy(buffer,str1,MAX_STRING_LENGTH);
        if(strlen(str1) < MAX_STRING_LENGTH){
            strncat(buffer,str2,MAX_STRING_LENGTH - strlen(buffer));
        }
        buffer[MAX_STRING_LENGTH - 1] = '\0';
        return buffer;
    }
    
    int main(int argc,char *argv[]){
        printf("%s",strcat_const("Hello ","world"));    //Prints "Hello world"
        return 0;
    }
    

    If both strings together are more than 1000 characters long, it will cut the string at 1000 characters. You can change the value of MAX_STRING_LENGTH to suit your needs.

提交回复
热议问题