首页 > 技术文章 > C 风格字符串相加

lucy-lizhi 2017-02-28 21:44 原文

<<C++ Primer>> 第四版Exercise Section 4.3.1 的4.3.0 有如下题目:编写程序连接两个C风格字符串字面值,把结果存储在C风格字符串中。代码如下:

// 2_3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <ctime>

using namespace std;

int main()
{
	const char *pc1 = "hello";
	const char *pc2 = "world";
	char *pc = new char[strlen(pc1)+strlen(pc2)+1];
	while (*pc1)
	{
		*pc = *pc1;
		++pc;
		++pc1;
	}
	while (*pc2)
	{
		*pc = *pc2;
		++pc;
		++pc2;
	}
	*pc = '\0';
	pc = pc - 10;
	string str(pc);
	cout << str << endl;
	return 0;
}

  

程序输出如下:

 

这里只需要注意,最后打印的时候,需要把指针退回到字符串第一位上来,其次打印的时候,可以通过c++ string 对象的构造函数来做。

 

推荐阅读