Monday, November 11, 2013

Alternately Store Elements of Two Char Arrays

Recently I was asked a question, i.e. how to output two char arrays alternately. It is easy to work out, so the main point here may be to practice my writing skills and to increase the number of my blogs. By the way, record my solution. I chose to store them first and then you could do anything as you like. Maybe output it. Maybe pass it. Whatever.

#include <stdio.h>
#include <string.h>

int main()
{
    char a[512]={0}, b[512]={0}, buf[1024]={0};
    int i=0, length_a=0, length_b=0, minlength=0;
 
    scanf("%s", a);
    scanf("%s", b);

    length_a = strlen(a);
    length_b = strlen(b);
    minlength = length_a > length_b ? length_b : length_a;
    for(i=0; i<minlength; ++i)
    {
        buf[i*2] = a[i];
        buf[i*2+1] = b[i];
    }

    while (i < length_a)
    {
        buf[i+length_b] = a[i++];
    }

    while (i < length_b)
    {
        buf[i+length_a] = b[i++];
    }

    printf("%s", buf);

    return 0;
}





No comments:

Post a Comment