在字符串中找出连续最长的数字串, 返回最长数字串

要求:在字符串中找出连续最长的数字串, 返回最长数字串。
输入: 字符串
输出: 最长的数字字符串

思路:1、先逐字符第一次遍历输入的字符串,对非数字的的字符置0,将每一段连续的数字分别置为1-999999的数字,将获得的字符放入vector容器中;
2、求vector容器中最大的元素值及其对应的索引;
3、使用STL中string的函数substr(索引值 + 1 - 最大值, 最大值)求出想要的字符串;
4、使用递归函数findIntegerStr查找是否有多个最长连续数字字符串;

测试方法:1、输入:不含数字的字符串。 返回:未找到您要的字符串;
2、输入:含有数字的字符串(最长的数字连续字符串有且仅有一个)。 返回:最长的连续数字字符串;
3、输入:含有数字的字符串(最长数字连续字符串有多个)。 返回:返回所有的长度相等的且长度最长的连续数字字符串;

#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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43864187/article/details/104610952