5

文字列を複製してから値を連結したいとします。

stl std::string を使用すると、次のようになります。

string s = "hello" ;
string s2 = s + " there" ; // effectively dup/cat

Cで:

char* s = "hello" ;
char* s2 = strdup( s ) ; 
strcat( s2, " there" ) ; // s2 is too short for this operation

Cでこれを行う唯一の方法は次のとおりです。

char* s = "hello" ;
char* s2=(char*)malloc( strlen(s) + strlen( " there" ) + 1 ) ; // allocate enough space
strcpy( s2, s ) ;
strcat( s2, " there" ) ;

Cでこれを行うよりエレガントな方法はありますか?

4

5 に答える 5

4

あなたはそれを作ることができます:

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;
}
于 2012-09-25T21:18:10.230 に答える
3

あまり。C には、C++ のような優れた文字列管理フレームワークがありません。を使用して、malloc()あなたが示したように、あなたが求めているものに近づくことができます。strcpy()strcat()

于 2012-09-25T21:12:38.547 に答える
2

GLib のようなライブラリを使用して、その文字列型を使用できます。

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

GString の末尾に文字列を追加し、必要に応じて展開します。

于 2012-09-25T21:15:36.347 に答える