输入示例:
asdfgh245467sds12
输出示例:
245467
先放代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
int count = 0, pos = 0,v=0;//count用来记录最长数字串的数量,pos用来记录最长数字串起始的位置
string str;
cin >> str;
for (int i = 0; i<str.size(); i++)//这个循环用来找最长数字串的数量
{
if (str[i] >= '0'&&str[i] <= '9')
{
v++;
if (v>count)
{
count = v;
}
}
else
{
v = 0;
}
}
for (int i = 0; i<str.size(); i++)//这个循环用来判断最长数字串起始位置
{
if (str[i] >= '0'&&str[i] <= '9')
{
if (str[i - 1]<'0'||str[i - 1]>'9')
{
if (str[i + count-1]>'0'&&str[i + count-1] < '9')
{
pos = i;
}
}
}
}
for (int i = 0; i<count; i++)//打印字符串
{
cout << str[i + pos];
}
}
以下是我觉得重要的代码
for (int i = 0; i<str.size(); i++)
{
if (str[i] >= '0'&&str[i] <= '9')
{
if (str[i - 1]<'0'||str[i - 1]>'9')
{
if (str[i + count-1]>'0'&&str[i + count-1] < '9')
{
pos = i;
}
}
}
}
for (int i = 0; i<count; i++)
找到最长字符串的位置很关键,此处我用了一个循环和三个条件判断语句来确定这个位置是否为最长字符串的起始位置
第一个if语句判断这个位置的字符是否是数字
第二个if语句判断这个位置的前一个位置的字符是否为字母
第三个if语句判断这个位置是否是最长数字串的起始位置
都满足条件即这个位置是最长字符串的起始位置
然后起始位置开始输出count个数字就得到了最长字符串。