问题
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?
回答1:
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;
}
回答2:
Not really. C simply doesn't have a good string management framework like C++ does. Using malloc()
, strcpy()
and strcat()
like you have shown is about as close as you can get to what you are asking for.
回答3:
You could use a library like GLib and then use its string type:
GString * g_string_append (GString *string, const gchar *val);
Adds a string onto the end of a GString, expanding it if necessary.
回答4:
A GNU extension is asprintf() that allocates the required buffer:
char* s2;
if (-1 != asprintf(&s2, "%s%s", "hello", "there")
{
free(s2);
}
回答5:
Inspired by nightcracker, I also thought of
// 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 ;
}
来源:https://stackoverflow.com/questions/12591074/is-there-a-neat-way-to-do-strdup-followed-by-strcat