1、循环比较查找为数字字符并且存入到一个字符串中,采用multimap存放对应字串与长度,并通过大小排序; 2、将排序后的map中的子串有相同长度的合并输出,用一个vcetor转存一次方便输出;
#include <iostream>
#include <map>
#include <string>
#include <bits/stdc++.h>
using namespace std;
struct CharCount {
bool operator()(const string& i, const string &j) { // 从大到小排序
return i.length() >= j.length();
}
};
int main()
{
string str;
while (getline(cin, str)) {
int cnt = 0;
string tmpstr;
multimap<string, int, CharCount> v1;
v1.clear();
for (int i = 0; i < str.length(); i++) {
bool flag = (str[i] >= '0') && (str[i] <= '9');
if (flag) {
tmpstr.push_back(str[i]);
if (i < str.length() - 1) { // 字符串最后一位是数字的情况
continue;
}
}
if (!tmpstr.empty()) { // 为空的字符串不插入
v1.insert(pair<string, int>(tmpstr, tmpstr.length())); //已经按子串长度排序后插入
}
if (!flag) { // 不是数字的字符清除
tmpstr.clear(); // 清除前一次的数字子串
}
}
vector<string> vec;
auto mm = v1.begin()->second; // 第一个为最长数字子串
for (auto& it = v1.begin(); it != v1.end(); it++) {
if (it->second == mm) { // 找到相同长度的子串
vec.insert(vec.begin(),it->first); // 从头部插入数字子串
}
}
for (auto& it : vec) {
cout << it; // 合并遍历输出相同长度的字串
}
cout << "," <<mm << endl; // 输出相同字串的长度
str.clear(); // 循环输入,清除上一次的字符串
}
return 0;
}