一、sort函数的默认排序:字典顺序
sort(S.begin(), S.end());
输出后即为:字典顺序
二、使用compare函数实现:先按照长度排序,再字典排序
//定义compare函数,先按长度排序,长度相同再按字典序
bool compare(string a, string b)
{
if (a.size() != b.size()) return a.size() > b.size();
else {
return a > b;
}
}
//排序
sort(S.begin(), S.end(), compare);
compare函数解释:当a与b长度不等时,按照长度递减的顺序排列;否则当a,b长度一致时,按照默认的字典顺序排列。
三、字符串的分割操作
我要写的题主要是截取末尾的字符。
1、一些无用但还是尝试了的小尝试
博主本人先想投机取巧,因为string类型的值末尾都隐含了一个’\0’作为字符串末尾,所以想直接将最末尾的单个字符改为’\0‘,经过VS编译输出以后是可以输出截取过的子字符串,但长度其实并未改变,所以:并不能直接修改。
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string S = "abcde";
cout << S.size() << endl;
S[S.size() - 1] = '\0';
cout << S << ' ' << S.size();
}
输出为:
5
abcd 5
2、substr函数
substr(int A,int B):A是提取子字符串的起始位置,B是要提取的长度
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string S = "abcde";
int n1 = S.size();
for (int j = 1; j < n1; j++)
{
string temp1 = S.substr(0, j);
cout << temp1<<endl;
}
}
输出为:
a
ab
abc
abcd
碎碎念:感觉这么多天的刷题也算是有了代码能力的进步!加油孩子们!