Is there a neat way to do strdup () followed by strcat ()?

Let's say I wanted to duplicate a string and then concatenate its value.

Using stl std :: string, this is:

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?

+4
source share
5 answers

You can do the following:

 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; } 
+4
source

Not really. C simply does not have a good string management structure such as C ++. Using malloc() , strcpy() and strcat() , as you showed, are about as close as you can get what you ask for.

+4
source

You can use a library like GLib and then use your string type :

GString * g_string_append (GString *string, const gchar *val);

Adds a string to the end of the GString, expanding it if necessary.

+2
source

The GNU asprintf() , which allocates the necessary buffer:

 char* s2; if (-1 != asprintf(&s2, "%s%s", "hello", "there") { free(s2); } 
+1
source

Inspired by the nightmare, I also thought about

 // writes s1 and s2 into a new string and returns it char* catcpy( char* s1, char* s2 ) { char* res = (char*)malloc( strlen(s1)+strlen(s2)+1 ) ; // A: sprintf( res, "%s%s", s1, s2 ) ; return res ; // OR B: *res=0 ; // write the null terminator first strcat( res, s1 ) ; strcat( res, s2 ) ; return res ; } 
0
source

Source: https://habr.com/ru/post/1436235/


All Articles