简体   繁体   中英

How would I merge these two arrays? C

I am working on a school assignment and I am having trouble figuring out how to merge these two arrays. I have to merge half of each array together into a third array. I am turning my tires, an I think I am over thinking what I have to do. I do not want to waste your time explaining all the things I have tried. Any help would be appreciated, also if you post any code can you explain to me what it is doing, because I want to understand what is happening (as much as possible) Thanks in advance!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 254    

int main()
{

Capturing the string here using user input

    char string_1[SIZE];
    printf( "Please enter a long string: " );
    fgets ( string_1, SIZE, stdin );

Getting the string length to calculate byte sizes

    size_t ln = strlen(string_1) - 1;
    if (string_1[ln] == '\n')
        string_1[ln] = '\0';    

Repeated...

    char string_2[SIZE];
    printf( "Please enter a long string: " );
    fgets ( string_2, SIZE, stdin );
    size_t ln2 = strlen(string_2) - 1;
    if (string_1[ln2] == '\n')
        string_1[ln2] = '\0';

Printing the byte size of the two strings.

    printf("String 1 is %zu bytes long, and String 2 is %zu bytes long", ln, ln2);  

I would like to concat

    return 0;


}

check this code which uses strncpy

char string_3[2*SIZE + 1];    
strncpy(string_3, string_1, strlen(string_1)/2);
string_3[strlen(string_1)/2] = '\0';
strncpy((string_3 + strlen(string_3)), string_2, strlen(string_2)/2);
string_3[strlen(string_1)/2 + strlen(string_2)/2] = '\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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM