这是一个string的函数
作用:
把字符串 s 的前 n 个字符赋给当前的字符串
string& assign(const char* s , int n)
为研究他,我定义了三个string量
string str1;
str1 = "noproblem";
string str2;
str2.assign(str1, 5);
string str3;
str3.assign("noproblem", 5);
目的肯定是拷贝 noproblem 的前5个字符。
然后写一个简单代码,打印这三个字符串
#include<iostream>
using namespace std;
void test01()
{
string str1;
str1 = "noproblem";
cout << "str1=" << str1 << endl;
string str2;
str2.assign(str1, 5);
cout << "str2=" << str2 << endl;
string str3;
str3.assign("noproblem", 5);
cout << "str3=" << str3 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
结果如下:
很明显,
一个是去除了前5个字符
一个是拷贝了前5个字符
所以大家以后用assign函数时要注意这个细节哦!