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

C++中的string

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

C++中的string

string的增很简单,直接用”+“,”+=“操作符,可以方便的对字符串进行添加

int main() {
	string s1;
	string s2;
	s1 = "abc";
	s2 = "abc";
	cout << s1 + s2 << endl;
	return 0;
}

//输出  abcabc
append()操作
int main() {
	string s1;
	string s2;
	s1 = "str1";
	s2 = "str2";
	s1.append("123");  //直接添加字符串至尾部
	cout << s1 << endl;
	s1.append("1230", 2); //从参数字符串起始位置开始添加2个字符到s1
	cout << s1 << endl;
	s1.append(s2, 0, 1);  //把s2的区间[0,1)的字符添加至s1
	cout << s2 << endl << s1 << endl;
	return 0; 
}

append是把参数添加至字符串的尾部,参数字符串可以是string,也可以是c_str,在参数字符串的后面可以参数字符串的起始位置和结束位置。总结为:append(string,[start,end))。

push_back()

push_back()可以在string的后面添加一个字符 

string str1("str1");
str1.push_back('a');
cout << str1 << endl;

 

insert

insert可以指定位置在目标string中插入。

string str1("str1");
str1.insert(0, "insert");  //从0开始插入参数字符串
cout << str1 << endl;
str1.insert((string::size_type)0, 2, '0'); //在指定位置插入2个'0',用size_type强转不会产生歧义
cout << str1 << endl;
str1.insert(str1.begin(), 3, 'b'); //迭代器指定位置后面插入3个'b'
cout << str1 << endl;

 删:

erase:

string str1("string1");
str1.erase(0, 1); //删除指定区间
cout << str1 << endl;
str1.erase(2);  //指定删除的起始位置,直至末尾
cout << str1 << endl;

pop_back()

int main() {
	string str1("string1");
	str1.pop_back(); //从尾部弹出字符
	cout << str1 << endl;
}

 

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

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

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