String容器

1.string基本概念

2.string构造函数

构造函数原型:


string();         创建一个空的字符串

string(const char*s); 使用字符串s初始化

string(const string& str); 使用一个string对象初始化另一个string对象

string(int n,char c); 使用n个字符c来初始化

代码:

#include<iostream>
using namespace std;
#include<string>
void test()
{
	const char *str="hello world";
	
	string s2(str);
	cout<<s2<<endl;
	
	string s3(s2);
	cout<<s3<<endl;
	
	string s4(5,'a'); 
	cout<<s4<<endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

3.string-赋值操作

string赋值方式 :1.等号赋值  2.assign赋值 

代码:

#include<iostream>
using namespace std;
#include<vector>
//string赋值方式 :1.等号赋值  2.assign赋值 
void test()
{
	//1.等号赋值 
	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;
	
	//2.assign赋值 
	string str4;
	str4.assign("I love you");
	cout<<"str4= "<<str4<<endl;
	
	string  str5;
	str5.assign(str4);
	cout<<"str5= "<<str5<<endl;
	
	string str6;
	str6.assign("I love you",5);
	cout<<"str6= "<<str6<<endl;
	
	string str7;
	str7.assign(10,'l');
	cout<<"str7= "<<str7<<endl;
}

int main()
{
	
	test();
	system("pause");
	return 0;
 } 

4. string字符串拼接

函数原型

string& operator+=(const char* str);     //重载+=操作符

string& operator+=(const char c);     //重载+=操作符

string& operator+=(const string&  str);     //重载+=操作符

string& append(const char *s);       //把字符串s连接到当前字符串结尾

string& append(const char *s,int n);       //把字符串s的前n个字符连接到当前字符串的结尾

string& append(const string &s);    // 同operator+=(const string& str)

string& append(const string &s,int pos,int n);  //字符串s中从pos开始的n个字符连接到字符串的结尾

代码:

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

void test()
{
	//1
	string str1;
	str1+="YOU";
	cout<<"str1= "<<str1<<endl;
	//2.
	str1+='cc';
	cout<<"str1= "<<str1<<endl;
	//3.
	string str2="like me";
	str1+=str2;
	cout<<"str1= "<<str1<<endl;
	//4.
	string str3="I";
	str3.append(" love ");
	cout<<"str3= "<<str3<<endl;
	//5.
	str3.append("games",4);
	cout<<"str3= "<<str3<<endl;
	
}

int main()
{
	test();
	system("pause");
	return 0;
 } 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值