Requirement: Find the longest continuous number string in the string, and return the longest number string.
Input: string
Output: longest string of numbers
Ideas: 1. First traverse the input string character by character, set 0 for non-digit characters, set each continuous number to numbers from 1-999999, and put the obtained characters into the vector container;
2. Find the maximum element value in the vector container and its corresponding index;
3. Use the function substr (index value + 1-maximum, maximum) of string in STL to find the desired string;
4. Use recursive function findIntegerStr finds whether there are multiple longest continuous numeric strings;
Test method: 1. Input: string without numbers. Return: the string you want was not found;
2. Input: a string containing numbers (the longest string of numbers has only one). Return: the longest string of consecutive numbers;
3. Input: string containing numbers (there are multiple consecutive strings of longest numbers). Return: Return all consecutive numeric strings with the same length and the longest length;
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
string str; //待输入的字符串
string subStr; //想要输出的子串
int max_val; //最大数字子串长度
int max_val_distance; //最大数字子串最后一位对应的索引
template<class T>
void myPrint(T val) //用于编写遍历vector的函数,可同下面的函数一起删除
{
cout << val << " ";
}
template<class T>
void printVector(vector<T> v) //遍历vector中的元素
{
for_each(v.begin(), v.end(), myPrint<T>);
}
void findIntegerStr(string str, vector<int> vec, int max_val, int max_val_distance)
{
if (max_val != 0)
{
cout << "您想要输出的最长连续数字字符串为:" << str.substr(max_val_distance + 1 - max_val, max_val) << "; " << endl;
vec[max_val_distance] = 0;
vector<int>vec1 = vec;
int max_val1 = 0, max_val_distance1 = 0;
vector<int>::iterator max1 = max_element(vec1.begin(), vec1.end());
max_val1 = *max1;
max_val_distance1 = distance(vec1.begin(), max1);
if (max_val_distance1 > max_val_distance)
{
return findIntegerStr(str, vec1, max_val1, max_val_distance1);
}
else
{
cout << "上面就是您想要输出的所有字符串!!!" << endl;
}
}
else
{
cout << "未找到您要的连续数字字符串!" << endl;
return;
}
}
int main()
{
cout << "请手动输入字符串:";
cin >> str;
int len = str.size(); //字符串长度
string str2 = str;
vector<int> vec;
int j = 0;
for (auto i = 0; i < len; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
j++;
str[i] = j;
vec.push_back(str[i]);
}
else
{
j = 0;
str[i] = 0;
vec.push_back(str[i]);
}
}
vector<int>::iterator max = max_element(vec.begin(), vec.end());
max_val = *max;
int max_val_distance = distance(vec.begin(), max);
findIntegerStr(str2, vec, max_val, max_val_distance);
system("pause");
return 0;
}