[英]Concatenating two arrays
I was trying to create a program that takes in two arrays and concatenates them to create a new string. 我试图创建一个接受两个数组并将它们连接起来以创建新字符串的程序。 These are the two strings. 这是两个字符串。
char a[8]={"hellostr"};
char b[8]={"HELLOSTR"};
Can someone tell me how could I concatenate and display this concatenated string? 有人可以告诉我如何串联并显示此串联的字符串吗? I tried looking for it but could not understand much of it. 我尝试寻找它,但对它了解不多。
You need to make use of strcat()
function from string.h
. 您需要使用string.h
的strcat()
函数。
A sample algo: 样本算法:
destarr[128]
, for example) large enough to hold the result (concatenated string). 定义一个足够大的数组(例如destarr[128]
)以容纳结果(连接的字符串)。 memset()
the destarr
to 0
. memset()
destarr
为0
。 strcat(destarr, a)
and strcat(destarr, b)
to concatenate one after another. 使用strcat(destarr, a)
和strcat(destarr, b)
彼此串联。 That said, 那就是
char a[ ]={"hellostr"};
is considered better and less error-prone over 被认为是更好的,并且不易出错
char a[8]={"hellostr"};
as, 如,
strcat
function can be used. 可以使用strcat
函数。
Header - string.h
标头string.h
If you want to do that without strcat
function then you can write a simple function - 如果您想在没有strcat
函数的情况下执行此操作,则可以编写一个简单的函数-
void concatenate(char a[], char b[])
{
int c, d;
c = 0;
while (a[c] != '\0')
{
c++;
}
d = 0;
while (b[d] != '\0')
{
a[c] = b[d];
d++;
c++;
}
a[c] = '\0';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.