栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

string赋值操作一个小知识

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

string赋值操作一个小知识

这是一个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
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函数时要注意这个细节哦!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/766772.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号