C++函数返回两个 char 数组的相同索引元素



我知道这应该如何在我的脑海中工作,但由于某种原因我无法编码它。

我需要编写一个 c++ 函数,它接受两个字符数组并返回它们的"交叉乘积"(不是乘法(组合。

string crossProd(const char* a, const char* b, int sizeofa, int sizeofb)

例: 输入: A-->"ABC", B-->"123" 输出:A1B2C3

感谢您的任何帮助。

试试这个:

#include <iostream>
#include <string.h>
std::string crossProd( const char* a, const char* b, int sizeofa, int sizeofb)
{
std::string return_str = "";
if (sizeofb >= sizeofa)
{
for (int i=0; i<=sizeofa; i++)
{
return_str = return_str + a[i] +b[i];
}
for(int i=sizeofa+1; i<=sizeofb; i++)
{
return_str = return_str + b[i];
}
}
else
{
for (int i=0; i<=sizeofb; i++)
{
return_str = return_str + a[i] +b[i];
}
for(int i=sizeofb+1; i<=sizeofa; i++)
{
return_str = return_str + a[i];
}
}
return return_str;
}
int main()
{
const char* a = "Chitta";
const char* b = "123456";
std::cout<<a<<":"<<b<<":"<<crossProd(a,b,6,6)<<std::endl;
const char* a1 = "ChittaRanjan";
const char* b1 = "12345";
std::cout<<a1<<":"<<b1<<":"<<crossProd(a1,b1,12,5)<<std::endl;
const char* a2 = "Chitta";
const char* b2 = "12345678";
std::cout<<a2<<":"<<b2<<":"<<crossProd(a2,b2,6,8)<<std::endl;
return 0;
}

输出:

  • 奇塔:123456:C1h2i3t4t5a6

  • ChittaRanjan:12345:C1h2i3t4t5aRanjan

  • 奇塔:12345678:C1h2i3t4t5a678

注意: 这不是优化的代码。

您对术语cross-product的使用有点模棱两可。叉积是对三维空间中两个向量的二元运算。您显示为"交叉制作"的结果只是通过交替使用每个字符串中的字符将两个字符串折叠在一起,直到字符耗尽。

你从@ChittaRajan那里得到了很好的答案,但有很多方法可以解决这个问题。一方面,您可以简单地使用operator[]和索引来组合每个字符串中的常见字符,然后添加较长的字符中的剩余字符,例如:

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;
}

既然你已经使用了基本的char*类型,你可以简单地为每一个字符串提供一个指向原始字符.c_str()的指针和一对指针来完成同样的事情,例如

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;
}

在这两种情况下,当与简短示例配对时:

int main (void) {
std::string a {"abc"}, b {"123"}, c = fold (a, b);
std::cout << c << 'n';
}

示例使用/输出

您收到期望的输出:

$ ./bin/strfold
a1b2c3

查看两者,如果您有其他问题,请告诉我。

最新更新