Information
Total Authors: 15
Total Articles: 40
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)