The Open Code Project

Dynamically merge/concatenate two strings in C++

January 3rd,2010 by Allan Bogh

While learning C++, yes I'm a C++ newb at the moment, I read that the strcat function didn't dynamically resize strings. I decided to make a little helper function to dynamically resize strings while acting like the strcat function. It's called strmrg, takes two strings as parameters and returns a separate, merged string. It's nothing special but it makes for a better understanding of dynamic string allocation.
 

#include <string.h>
using namespace std; //just because

/**
 * strmrg concatenates str2 with str1 so that the result is str1str2.
 * Dynamic size allocation prevents the need to allocate a bigger char array.
 * Original strings are not modified.
 * @param str1 - a string to append onto
 * @param str2 - a string to append to str1
 * @return A new string which looks like str1str2
 */
char* strmrg(char* str1,char* str2){
    //make a new null string of the combined length
    char* outstr = new char[strlen(str1)+strlen(str2)];
    //copy the first string to the output variable
    strcpy(outstr,str1);
    //concatenate the second string to the output variable
    strcat(outstr,str2);

    return outstr;
}


 

Comments (0)


:

:

:


: formatting help
Close

Formatting instructions:

You can use <a> tags but everything else will be stripped and your comment will look funny.

I swear, don't use html except the <a> tag or else some random star will supernova. Remember, we have a star right next to us, so don't try it.

This isn't bbcode either so don't use it. That is all.