C++字符串常用函数

天梯赛中常有一道纯考察字符串的题目,如果熟练使用这些字符串函数,就会节省很多时间。

我们,浅看一下。

第一个定义,C++中要定义一个字符串类型的数据直接:String <字符串名>。这个应该不用多说。

第二,C++中给字符串赋值,str = “helloworld!”;这个直接写即可,输入的话直接cin >> str;即可。

第三个string s1(5,‘a’);,意思是定义一个字符串s1,由5个a字符组成。算是一个初始化了。

第四个,s1.push_back(‘b’);在s1字符串后面添加一个字符b。

第五个,s1.insert(s1.begin(),‘i’);在字符串s1前面插入字符i。

第六个,s1.insert(s1.end(),‘i’);在字符串s1后面插入字符i。

第七个,s1.find(s3),判断s3是不是s1的字串,如果是,返回s3在s1中的位置,如果不是,返回18446744073709551615,这个很大的数是二进制下64位1,也就是-1。(狗头)所以判断时候可以这样用,s1.find(s3) == -1。

第八个,字符串可以直接排序,sort(s1.begin(),s1.end())。

第九个,s1.substr(2,4)从第二个位置开始取四个字符。

自己捣鼓捣鼓才能更好的明白:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	string str;
	str = "helloworld!";
	string s2(str);
	cout << s2 << endl;
	string s1(5,'a');
	cout << s1 << endl;
	s1.push_back('b');
	cout << s1 << endl;
	s1.insert(s1.begin(),'i');
	cout << s1 << endl;
	s1.insert(s1.end(),'i');
	cout << s1 << endl;
	string s3 = "i";
	cout << s1.find(s3) << endl;
	s3 = "b";
	cout << s1.find(s3) << endl;
	s3 = "ab";
	cout << s1.find(s3) << endl;
	s3 = "o";
	cout << (s1.find(s3)==-1) << endl;
	sort(s1.begin(),s1.end());
	cout << s1 << endl;
	cout << s1.substr(2,4) << endl;
	cout << s1 << endl;	
}
  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三元湖有大锦鲤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值