C string append

CString

C Problem Overview


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

new_str = strcat(str1, str2);

This command changes the value of str1. I want new_str to be the concatanation of str1 and str2 and at the same time str1 is not to be changed.

C Solutions


Solution 1 - C

You need to allocate new space as well. Consider this code fragment:

char * new_str ;
if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
    new_str[0] = '\0';   // ensures the memory is an empty string
    strcat(new_str,str1);
    strcat(new_str,str2);
} else {
    fprintf(STDERR,"malloc failed!\n");
    // exit?
}

You might want to consider strnlen(3) which is slightly safer.

Updated, see above. In some versions of the C runtime, the memory returned by malloc isn't initialized to 0. Setting the first byte of new_str to zero ensures that it looks like an empty string to strcat.

Solution 2 - C

do the following:

strcat(new_str,str1);
strcat(new_str,str2);

Solution 3 - C

Consider using the great but unknown open_memstream() function.

FILE *open_memstream(char **ptr, size_t *sizeloc);

Example of usage :

// open the stream
FILE *stream;
char *buf;
size_t len;
stream = open_memstream(&buf, &len);

// write what you want with fprintf() into the stream
fprintf(stream, "Hello");
fprintf(stream, " ");
fprintf(stream, "%s\n", "world");

// close the stream, the buffer is allocated and the size is set !
fclose(stream);
printf ("the result is '%s' (%d characters)\n", buf, len);
free(buf);

If you don't know in advance the length of what you want to append, this is convenient and safer than managing buffers yourself.

Solution 4 - C

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

Solution 5 - C

You could use asprintf to concatenate both into a new string:

char *new_str;
asprintf(&new_str,"%s%s",str1,str2);

Solution 6 - C

I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");

    int i;
    for (i = 0; i < 10; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

Solution 7 - C

strcpy(str1+strlen(str1), str2);

Solution 8 - C

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);
}

Solution 9 - C

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

Solution 10 - C

You can try something like this:

strncpy(new_str, str1, strlen(str1));
strcat(new_str, str2);

More info on strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUdara S.S LiyanageView Question on Stackoverflow
Solution 1 - CCharlie MartinView Answer on Stackoverflow
Solution 2 - CVirtualTrollView Answer on Stackoverflow
Solution 3 - CChristophe QuintardView Answer on Stackoverflow
Solution 4 - CJoel FalcouView Answer on Stackoverflow
Solution 5 - CfrmdstryrView Answer on Stackoverflow
Solution 6 - CWeiView Answer on Stackoverflow
Solution 7 - CBarun ParichhaView Answer on Stackoverflow
Solution 8 - CZacView Answer on Stackoverflow
Solution 9 - Cmaheshgupta024View Answer on Stackoverflow
Solution 10 - CSitnikView Answer on Stackoverflow