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
.
A sample algo:
destarr[128]
, for example) large enough to hold the result (concatenated string). memset()
the destarr
to 0
. strcat(destarr, a)
and strcat(destarr, b)
to concatenate one after another. That said,
char a[ ]={"hellostr"};
is considered better and less error-prone over
char a[8]={"hellostr"};
as,
strcat
function can be used.
Header - string.h
If you want to do that without strcat
function then you can write a simple function -
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';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.