Say I wanted to duplicate a string then concatenate a value to it.
Using stl std::string, it's:
string s = "hello" ;
string s2 = s + " there" ; // effectively dup/cat
in C:
char* s = "hello" ;
char* s2 = strdup( s ) ;
strcat( s2, " there" ) ; // s2 is too short for this operation
The only way I know to do this in C is:
char* s = "hello" ;
char* s2=(char*)malloc( strlen(s) + strlen( " there" ) + 1 ) ; // allocate enough space
strcpy( s2, s ) ;
strcat( s2, " there" ) ;
Is there a more elegant way to do this in C?
You could make one:
char* strcat_copy(const char *str1, const char *str2) {
int str1_len, str2_len;
char *new_str;
/* null check */
str1_len = strlen(str1);
str2_len = strlen(str2);
new_str = malloc(str1_len + str2_len + 1);
/* null check */
memcpy(new_str, str1, str1_len);
memcpy(new_str + str1_len, str2, str2_len + 1);
return new_str;
}
A GNU extension is asprintf()
that allocates the required buffer:
char* s2;
if (-1 != asprintf(&s2, "%s%s", "hello", "there")
{
free(s2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With