C语言 连接两个字符数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3324826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:59:46  来源:igfitidea点击:

Concatenate two char arrays?

cstringstring-concatenation

提问by ingh.am

If I have two char arrays like so:

如果我有两个像这样的字符数组:

char one[200];
char two[200];

And I then want to make a third which concatenates these how could I do it?

然后我想制作一个将这些连接起来的第三个我该怎么做?

I have tried:

我试过了:

char three[400];
strcpy(three, one);
strcat(three, two);

But this doesn't seem to work. It does if oneand twoare setup like this:

但这似乎不起作用。如果one并且two是这样设置的,它会这样做:

char *one = "data";
char *two = "more data";

Anyone got any idea how to fix this?

任何人都知道如何解决这个问题?

Thanks

谢谢

采纳答案by Martin Ingvar Kofoed Jensen

If 'one' and 'two' does not contain a '\0' terminated string, then you can use this:

如果 'one' 和 'two' 不包含以 '\0' 结尾的字符串,那么你可以使用这个:

memcpy(tree, one, 200);
memcpy(&tree[200], two, 200);

This will copy all chars from both one and two disregarding string terminating char '\0'

这将复制一个和两个中的所有字符,而不管字符串终止字符 '\0'

回答by EricSchaefer

strcpy expects the arrays to be terminated by '\0'. Strings are terminated by zero in C. Thats why the second approach works and first does not.

strcpy 期望数组以 '\0' 终止。字符串在 C 中以零结尾。这就是为什么第二种方法有效而第一种方法无效的原因。

回答by OverloadedCore

You can easily use sprintf

您可以轻松使用 sprintf

char one[200] = "data"; // first bit of data
char two[200] = "more data"; // second bit of data
char three[400]; // gets set in next line
sprintf(three, "%s %s", one, two); // this stores data