天梯赛中常有一道纯考察字符串的题目,如果熟练使用这些字符串函数,就会节省很多时间。
我们,浅看一下。
第一个定义,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;
}