题目描述
对输入的单词进行字典序排序输出: 字典序定义 1. 单词中字母比较不区分大小写,两个单词先以第一个字母作为排序的基准,如果第一个字母相同,就用第二个字母为基准,如果第二个字母相同就以第三个字母为基准。依此类推,如果到某个字母不相同,字母顺序在前的那个单词顺序在前。 2. 当一个短单词和一个长单词的开头部分都相同(即短单词是长单词从首字母开始的一部分),短单词顺序在前。 3. 字母大小写不同的相同单词,只输出一次。
输入描述:
不超过255个字符中,单词间用空格进行分隔,为简单起见,单词不包含连字符,无其它标点符号输出描述:
输出排序后的单词,单词之间用空格隔开(最后不带空格),重复的单词只输出一次。
示例1
输入
Hello hello world
输出
Hello world
#include <stdio.h> #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c) { std::string::size_type pos1, pos2; // cout<<c<<endl; pos2 = s.find(c.c_str()); pos1 = 0; // cout<<pos2<<endl; while(std::string::npos != pos2) { v.push_back(s.substr(pos1, pos2-pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if(pos1 != s.length()) { v.push_back(s.substr(pos1)); cout<<s.substr(pos1)<<endl; } } void strsplit(std::string s, char delim, std::vector<std::string>& vecstrs) { size_t last = 0; size_t index=s.find_first_of(delim, last); while (index!=std::string::npos) { if (s.substr(last, index-last) != "") vecstrs.push_back(s.substr(last, index-last)); last=index+1; index=s.find_first_of(delim,last); } if (index-last>0) { vecstrs.push_back(s.substr(last,index-last)); } } int main(int argc, char** argv) { // string str; char str[255]; vector<string> vs; // cin>>str; // str = cin.get(); // cin.getline(str, 100); gets(str); // SplitString(str, vs, " "); strsplit(str, ' ', vs); cout<<vs.size()<<endl; sort(vs.begin(),vs.end());//用sort函数对vector对象中存放的字符串排序,这里忽略了字母的大小写. string tmp_str = vs[0]; cout<<tmp_str<<endl; for(int i=1;i<vs.size();i++) { // cout<<tmp_str<<", "<<vs[i]<<endl; // if(strcmpi(tmp_str.c_str(), vs[i].c_str()) != 0) // cout<<strcasecmp(tmp_str.c_str(), vs[i].c_str())<<endl; int flag = strcasecmp(tmp_str.c_str(), vs[i].c_str()); if (flag != 0) { // cout<<tmp_str<<", "<<vs[i]<<endl; tmp_str = vs[i]; cout<<tmp_str<<endl; } // if(strcasecmp(tmp_str.c_str(), vs[i].c_str())) // { // cout<<vs[i]<<endl; // tmp_str=vs[i]; // } } return 0; }
参考链接:
https://blog.csdn.net/cnd2449294059/article/details/73871395