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
请按任意键继续. . .