讀入一個字符串str,輸出字符串str中的連續最長的數字串
輸入描述:
測試輸入包含1個測試用例,一個字符串str,長度不超過255。
輸出描述:
在一行內輸出str中裏連續最長的數字串。
輸入例子: abcd12345ed125ss123456789
輸出例子:123456789
解題思路
- 首先遍歷字符串,找到連續的數字串
- 把這一部分數字串遍歷完後,記錄數字串長度,繼續往後遍歷
- 與後面的數字串長度進行比較,如果大於之前的就更新最大數字串
- 輸出剛剛標記的數字串
代碼
#include<iostream>
#include<string>
using namespace std;
void Findnum(string str)
{
size_t i = 0;
int count = 0;//計數
int maxnum = 0;//標記最大數字串長度
int pos = 0;//最大數字串的開始位置
while (i < str.size())
{
while (!isdigit(str[i]))
i++;//不是數字就往後走
while (isdigit(str[i]))
{
count++;
i++;
}
if (count>maxnum)
{
maxnum = count;//更新maxnum
pos = i - maxnum;//標記pos
}
count = 0;
}
for (int j = pos; j < pos+maxnum; j++)
{
cout << str[j] ;
}
}
int main()
{
string str="abcd12345ed125ss123456789";
Findnum(str);
system("pause");
return 0;
}