Well, the code works only when the two strings are equal in size. But when the two strings arent equal in size, infinite loop occurs.
Do you have any idea what's wrong?
Thank you in advance.
First you need to find out the length of the shortest string. Then you merge the two strings for the length of the shortest. If one string is longer then you just add the rest of the longest string to the output.
I have written an example but used pointers so I am not sure if it would help you.
First you need to find out the length of the shortest string.
You don't actually need to find out the length of either string before traversing them. It's simpler to just depend on encountering the nul terminator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void intermix(constchar* a, constchar* b, char* result)
{
unsigned a_idx = 0;
unsigned b_idx = 0;
unsigned r_idx = 0;
while (a[a_idx] || b[b_idx])
{
if (a[a_idx])
result[r_idx++] = a[a_idx++];
if (b[b_idx])
result[r_idx++] = b[b_idx++];
}
result[r_idx] = '\0';
}
I think it's a little cleaner without the array subscript notation:
1 2 3 4 5 6 7 8 9 10 11 12
void intermix(constchar* a, constchar* b, char* result)
{
while (*a || *b)
{
if (*a)
*result++ = *a++;
if (*b)
*result++ = *b++;
}
*result = '\0';
}