您的位置:首页 > 其它

给出一个函数来合并两个字符串A和B

2013-04-05 19:23 281 查看
给出一个函数来合并两个字符串A和B。字符串A的后几个字节和字符串B的前几个字节重叠。

下面上代码:

#include <iostream>
using namespace std;

void copyStr(char pachar[], char pbchar[], int alen, int blen, char* &result)
{
	 int posa = 0;
	 int posb = 0;
	 int pos = 0;
	 int sz = alen+blen-1;
	 while (pos < sz && posa < alen && posb < blen)
	 {
		 while (pachar[posa]!=pbchar[0] && posa < alen)		//先在a中找到与b串第一个想匹配的元素。			
		 {
			 result[pos++] = pachar[posa++]; 
		 }
		 if (posa == alen)
		 {
			 while (posb < blen)
			 {
				 result[pos++] = pbchar[posb++];
			 }
		 }
		 else
		 {
			 int sa = posa;
			 while (pachar[posa] == pbchar[posb] && posa < alen && posb < blen) //检查一下是不是完全重叠。
			 {
				 posa++;
				 posb++;
			 }
			 if (posa == alen)	
			 {
				while (posb < blen)
				{
					result[pos++] = pbchar[posb++];
				}
			 }
			 else 
			 {
				 posa = sa;
				 posb = 0;
				 result[pos++] = pachar[posa++];
			 }
		 }
	 }
	 result[pos] = '\0';
}
int main()
{
	char pachar[] = "asdfvxcbnbvcxzghgh"; 
	char pbchar[] = "ghjklqwe";
	int alen = strlen(pachar);
	int blen = strlen(pbchar);
	char* result = new char[alen+blen-1];
	copyStr(pachar, pbchar, alen, blen, result);
	cout<<result<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐