Your use of the term cross-product
is a bit ambiguous. A Cross product is a binary operation on two vectors in 3-Dimensional space. The result you show as a "cross-produce" is simply folding two strings together by alternating characters from each of the strings until the characters are exhausted.
You have a good answer from @ChittaRajan, but there are numerous ways to approach the problem. On one hand you can simply use operator[]
and an index to combine common characters from each string and then add the remaining characters from whichever is longer, e.g.:
std::string fold (const std::string& a, const std::string& b)
{
std::string s {};
size_t i = 0, j;
while (a[i] && b[i]) { /* alternating add from a & b */
s += a[i];
s += b[i++];
}
j = i;
while (a[i]) /* if a longer, add remaining chars */
s += a[i++];
while (b[j])
s += b[j++]; /* if b longer, add remaining chars */
return s;
}
Of since you have made use of the basic char*
type, you can simply us a pointer to the raw character .c_str()
for each string and a pair of pointers to accomplish the same thing, e.g.
std::string fold (const std::string& a, const std::string& b)
{
std::string s {};
const char *pa = a.c_str(), *pb = b.c_str();
while (*pa && *pb) { /* alternating add from a & b */
s += *pa++;
s += *pb++;
}
while (*pa) /* if a longer, add remaining chars */
s += *pa++;
while (*pb)
s += *pb++; /* if b longer, add remaining chars */
return s;
}
In both cases when paired with a short example:
int main (void) {
std::string a {"abc"}, b {"123"}, c = fold (a, b);
std::cout << c << '\n';
}
Example Use/Output
You receive the desire output:
$ ./bin/strfold
a1b2c3
Look over both and let me know if you have further questions.