两个阵列的联合交替值?

时间:2021-06-21 12:19:58

I have two arrays of char: a,b. How can i create with a loop "for" the new array vet, which is the union of the two alternating array a, b?

我有两个char数组:a,b。如何创建一个循环“for”新数组vet,这是两个交替数组a,b的并集?

#include <stdio.h>

int main(void) {
    char a[] = "BNSIO";
    char b[] = "EISM\a";
    char vet[sizeof(a) + sizeof(b)];
    for (int i = 0; i < (sizeof(a) + sizeof(b)); i++) {

    }
    for (int i = 0; i < (sizeof(a) + sizeof(b)); i++){
        printf("%c", vet[i]);
    }
}

2 个解决方案

#1


0  

For alternating values from both arrays, try this (assuming lengths are equal):

对于来自两个数组的交替值,请尝试此操作(假设长度相等):

int main()
{
    int i;
    char a[] = "BNSIO";
    char b[] = "EISM\a";
    char vet[sizeof(a) + sizeof(b)];

    for( i = 0; i < sizeof(a); i++) {
        vet[2*i] = a[i];
        vet[2*i+1] = b[i];
    }

    for(i = 0; i < sizeof(vet) ; i++){
        printf("%c", vet[i]);
    }
}

#2


2  

You can try this:

你可以试试这个:

for (int i = 0,j=0,k=0; k < (sizeof(a) + sizeof(b) -2);) 
{
    if(i+1<sizeof(a))
    {
        vet[k] = a[i];
        i++;k++;
    }
    if(j+1<sizeof(b))
    {
        vet[k] = b[j];
        j++;k++;
    }       
}
for (int i = 0; i < (sizeof(a) + sizeof(b)-2); i++){
    printf("%c", vet[i]);
}

You need to subtract 1 for the null terminating character

您需要为空终止字符减去1

#1


0  

For alternating values from both arrays, try this (assuming lengths are equal):

对于来自两个数组的交替值,请尝试此操作(假设长度相等):

int main()
{
    int i;
    char a[] = "BNSIO";
    char b[] = "EISM\a";
    char vet[sizeof(a) + sizeof(b)];

    for( i = 0; i < sizeof(a); i++) {
        vet[2*i] = a[i];
        vet[2*i+1] = b[i];
    }

    for(i = 0; i < sizeof(vet) ; i++){
        printf("%c", vet[i]);
    }
}

#2


2  

You can try this:

你可以试试这个:

for (int i = 0,j=0,k=0; k < (sizeof(a) + sizeof(b) -2);) 
{
    if(i+1<sizeof(a))
    {
        vet[k] = a[i];
        i++;k++;
    }
    if(j+1<sizeof(b))
    {
        vet[k] = b[j];
        j++;k++;
    }       
}
for (int i = 0; i < (sizeof(a) + sizeof(b)-2); i++){
    printf("%c", vet[i]);
}

You need to subtract 1 for the null terminating character

您需要为空终止字符减去1