C string append

后端 未结 10 1265
野趣味
野趣味 2020-12-01 06:21

I want to append two strings. I used the following command:

new_str = strcat(str1, str2);

This command changes the value of str1

相关标签:
10条回答
  • 2020-12-01 06:49

    man page of strcat says that arg1 and arg2 are appended to arg1.. and returns the pointer of s1. If you dont want disturb str1,str2 then you have write your own function.

    char * my_strcat(const char * str1, const char * str2)
    {
       char * ret = malloc(strlen(str1)+strlen(str2));
    
       if(ret!=NULL)
       {
         sprintf(ret, "%s%s", str1, str2);
         return ret;
       }
       return NULL;    
    }
    

    Hope this solves your purpose

    0 讨论(0)
  • 2020-12-01 06:54

    You'll have to strncpy str1 into new_string first then.

    0 讨论(0)
  • 2020-12-01 06:54

    I needed to append substrings to create an ssh command, I solved with sprintf (Visual Studio 2013)

    char gStrSshCommand[SSH_COMMAND_MAX_LEN]; // declare ssh command string
    
    strcpy(gStrSshCommand, ""); // empty string
    
    void appendSshCommand(const char *substring) // append substring
    {
      sprintf(gStrSshCommand, "%s %s", gStrSshCommand, substring);
    }
    
    0 讨论(0)
  • 2020-12-01 07:01

    do the following:

    strcat(new_str,str1);
    strcat(new_str,str2);
    
    0 讨论(0)
提交回复
热议问题