![](https://i-blog.csdnimg.cn/blog_migrate/3204326cebda40a7ecde9047602c2302.png)
题目
解决代码及点评
/*
给出一个函数来合并两个字符串 A 和 B 。字符串 A 的后几个字节和字符串 B 的前几个字节重叠
重叠部分只要一份
*/
#include <iostream>
using namespace std;
void CopyStr(char *pszBuf1, char *pszBuf2, char *pszBuf3)
{
int nLen1 =strlen(pszBuf1);
int nLen2 =strlen(pszBuf2);
int nLen3 =nLen1 + nLen2 + 1;
int nPos1 = 0;
int nPos2 = 0;
int nPos3 = 0;
while (nPos1 < nLen1 - 1 && nPos2 < nLen2 - 1 && nPos3 < nLen3 - 1)
{
while (pszBuf1[nPos1] != pszBuf2[0] && nPos1 < nLen1 - 1)
{
pszBuf3[nPos3++] = pszBuf1[nPos1++];
}
if (nPos1 == nLen1 - 1)
{//pszBuf1完全结束,不存在重复
pszBuf3[nPos3++] = pszBuf2[nPos2++];
}
else
{//
int nTmpPos = nPos1;
while (pszBuf1[nPos1] == pszBuf2[nPos2] && (nPos1 < nLen1) && (nPos2 < nLen2))
{
nPos2++;
nPos1++;
}
if (nPos1 == nLen1)
{//完全重叠
nPos2 = 0;
while (nPos2 < nLen2)
{
pszBuf3[nPos3++] = pszBuf2[nPos2++];
}
}
else
{//不完全重叠,回复nPos1
nPos1 = nTmpPos;
nPos2 = 0;
pszBuf3[nPos3++] = pszBuf1[nPos1++];
}
}
}
}
int main()
{
char szBuf1[] = "aghgh";
char szBuf2[] = "ghjklqwe";
int nLen3 = strlen(szBuf1) + strlen(szBuf2) + 1;
char *pszResult = new char[nLen3];
int i;
for (i = 0; i < nLen3; i++)
{
pszResult[i] = 0;
}
pszResult[i-1] = '\0';
CopyStr(szBuf1, szBuf2, pszResult);
cout<<pszResult<<endl;
system("pause");
return 0;
}
代码下载及其运行
代码下载地址:http://download.csdn.net/detail/yincheng01/6704519
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行
程序运行结果