C++:拼接字符串

 

//例1.拼接字符串

#include<iostream>
using namespace std;

int main()
{
	string s1 = "Hello ";
	string s2 = "World! ";
	string s3 = " China";
	string s4;

	//第一种方式:append
	s4.append(s1);
	cout << s4.c_str() << endl;
	s4.append(s2);
	cout << s4.c_str() << endl;
	s4.append(s3);
	cout << s4.c_str() << endl;

	//第二种方式:+
	s4 += " welcome!";
	cout << s4 << endl;
	s4 = s4 + "libin";
	cout << s4 << endl;
}



//例2.使用str += "a", str = str + "a" 效率差距:
/*
str = str + "a"加的运算产生的是一个新的对象,再把结果返回,
而str += "a" 涉及到的应该是对象的引用,操作之后直接返回引用,
避免了产生新的对象。因此,两者的性能有一定的差距。
*/

#include <iostream>
#include <string>
#include<time.h>
using namespace std;

int main()
{
	static int num = 500000;
	time_t timeBegin, timeEnd;
	//开始
	timeBegin = time(NULL);
	string str = "";
	for (int i = 0; i < num; i++)
	{
		str = str + "a";
	}
	timeEnd = time(NULL);
	cout << "str=str +a所耗费的时间:" << timeEnd - timeBegin << " ms" << endl;

	//开始
	timeBegin = time(NULL);
	string str1 = "";
	for (int i = 0; i < num; i++)
	{
		str1 += "a";
	}
	timeEnd = time(NULL);
	cout << "str+=a所耗费的时间:" << timeEnd - timeBegin << " ms" << endl;

	return 0;
}

//输出结果
/*
str=str +a所耗费的时间:11 ms
str+=a所耗费的时间:0 ms
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值