如何多次附加到字符串?

mat*_*att 2 c string loops char

所以我有一个循环,每次生成一个sting,我想将此字符串追加到现有变量.

char fullString[] = "start: ";

while(x < 200){

    char someVar[] = "test "

    //append someVar to fullString

    x++;

}
Run Code Online (Sandbox Code Playgroud)

所以我想最终得到一个像这样的字符串:

start: test test test test test ...
Run Code Online (Sandbox Code Playgroud)

我可以轻松地使用任何其他语言,只是不知道如何做c,任何想法?

Gop*_*opi 5

你应该有一个足够大的缓冲区来容纳整个连接字符串.

使用字符串函数strcat(),如下所示

char fullString[2000] = "start: ";

while(x<200)
{
    char someVar[] = "test "; // What ever valid string you want to append to the existing string
    strcat(fullString,someVar);
    x++;
}
Run Code Online (Sandbox Code Playgroud)

  • 当心[Schlemiel的算法](http://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm#Schlemiel_the_Painter.27s_algorithm). (2认同)