I had to concatenate two ntcas (null terminated character arrays) that are alphabetically sorted. I tried first to do this using functions like strncat, strcat, but I just can't make the program to work properly.
Let's say that ntca1
is "ace"
and ntca2
is "bdfghz"
. I compare the first character from the two ntcas. I concatenate the character that had a smaller value to the result
ntca. I increment the index of the ntca from which the character was copied by 1.
This continues until one of the strings ends. Then the program copies any remaining from the other string to result
.
But ... I realised that I didn't know how to concatenate the character from a specific index of the source to the end of the destination ntca. Should I use the strcat or strncat?
In the second part of the problem, when one of the ntcas is over, how can I concatenate the remaining characters to result
?
This is what I have so far
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ char ntca1[251], ntca2[251], result[255];
unsigned int i, j, k, lenght_ntca1, lenght_ntca2;
cout << "Type the first ntca and press ENTER:";
cin.getline(ntca1, 251);
cout << "Type the second ntca and press ENTER:";
cin.getline(ntca2, 251);
cout << endl;
i = 0;
j = 0;
k = 0;
lenght_ntca1 = strlen(ntca1);
lenght_ntca2 = strlen(ntca2);
while (i<lenght_ntca1 && j<lenght_ntca2)
{ if (ntca1[i] <= ntca2[j])
{ result[k]=ntca1[i];
i++;
}
else if (ntca1[i] > ntca2[j])
{ result[k] = ntca2[j];
j++;
}
k++;
}
if (i == lenght_ntca1)
while (j<=lenght_ntca2)
{ result[k] = ntca2[j];
k++;
j++;
}
else if (j == lenght_ntca2)
while (i <= lenght_ntca1)
{ result[k] = ntca1[i];
k++;
i++;
}
cout << "The third ntca is: ";
cout << result;
cin.get();
}