【C++学习纪录】string容器——赋值操作

string赋值操作
1、string& operator=(const char* s) char* 类型字符串赋值给当前字符串
2、string& operator=(const string& s) string类型字符串赋值给当前字符串
3、string& operator=(char c) 把一个字符c赋值给当前字符串
4、string& assign(const char* s) char* 类型字符串赋值给当前字符串
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赋值给当前字符串

一、string& operator=(const char* s) char*类型字符串赋值给当前字符串

#include<iostream>
using namespace std;
#include<string>
int main()
{
    char *temp = "hello world";
    string str = temp;
    cout << str << endl;
    system("pause");
}

二、string& operator=(const string& s) string类型字符串赋值给当前字符串

#include<iostream>
using namespace std;
#include<string>
int main()
{
    string temp = "hello world";
    string str = temp;
    cout << str << endl;
    system("pause");
}

三、string& operator=(char c) 把一个字符c赋值给当前字符串

#include<iostream>
using namespace std;
#include<string>
int main()
{
	//注意:不可以string str = 'a',程序会报错。
    string str;
    str = 'a';
    cout << str << endl;
    system("pause");
}

四、string& assign(const char*s ,int n) 把字符串s的前n个字符赋值给当前字符串

#include<iostream>
using namespace std;
#include<string>
int main()
{
    const char *s = "hello world";
    string str;
    str.assign(s, 5);
    cout << str << endl;
    system("pause");
}

运行结果:

hello
请按任意键继续. . .

五、string& assign(int n, char c) 把n个字符c赋值给当前字符串

#include<iostream>
using namespace std;
#include<string>
int main()
{
    string str;
    str.assign(5, 'a');
    cout << str << endl;
    system("pause");
}

运行结果:

aaaaa
请按任意键继续. . .
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值