string 赋值操作和拼接

函数原型:

  1. string& operator =(const char* s); //char*类型字符串 赋值给当前的字符串
  2. string& operator =(const stirng &s); //把字符串s赋值给当前的字符串
  3. string& operator =(char c); //把字符赋值给当前的字符串
  4. string& assign(const char *s); //把字符串s赋值给当前的字符串
  5. string& assign(const char *s,int n); // 把字符串s的前n个字符赋值给 当前字符串
  6. string& assign(const string &s); //把字符串s赋值给当前字符串
  7. string& assign(int n, char c); //把n个字符c赋值给当前字符串
#include <iostream>
using namespace std;
#include <string>

void test()
{
	string str1;
	str1 = "hello world";
	cout<<"str1 "<<str1<<endl;

	string str2;
	str2 =str1;
	cout<<"str2  "<<str2<<endl;

	string str3;
	str3 = 'a';
	cout<<"str3  "<<str3<<endl;

	string str4;
	str4.assign("hello  c++");
	cout<<"str4  "<<str4<<endl;

	string str5;
	str5.assign("hello  c++",5);
	cout<<"str5  "<<str5<<endl;

	string str6;
	str6.assign(str5);
	cout<<"str6  "<<str6<<endl;

	string str7;
	str7.assign (10,'w');
	cout<<"str7  "<<str7<<endl;

}

int main()
{
	test();
	return 0;
}


在这里插入图片描述

拼接:

#include <iostream>
using namespace std;
#include <string>

void test()
{
	string  str1="我";
	str1 +="爱玩游戏";       //重载+=
	cout<<"str1  "<<str1<<endl;

	str1+=':';      //重载+=
	cout<<"str1  "<<str1<<endl;  

	string str2 ="LOL DNF";
	str1+=str2;       //重载+=
	cout<<"str1  "<<str1<<endl;

	string str3 ="I";
	str3.append("love");   //字符串拼接
	cout<<"str3  "<<str3<<endl;

	str3.append("game  cf",4);  //把字符串的前n个字符拼接到str3
	cout<<"str3  "<<str3<<endl;

	/*str3.append(str2);      //把str2拼接到str3后
	cout<<"str3  "<<str3<<endl;
*/
	/*str3.append(str2,0,3);
	cout<<"str3  "<<str3<<endl;*/
	str3.append(str2,4,3);//str2从第4个字符开始拼接3三字符到str3
	cout<<"str3  "<<str3<<endl;
}

int main()
{
	test();
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值