字符串中找出连续最长的数字串
本题不仅要知道最长字符串的长度,还需要输出这一串字符串,我的代码如下
#include <iostream>
#include <string>
int main()
{
int max=0, count = 0, first;//max为最长数字串的长度,count为当前数字串的长度,first为最长数字串的首位置
std::string a;
std::cin >> a;
for (int i = 0;i <= a.size();i++) {
if (a[i] >= '0'&&a[i] <= '9') {
count++;//倘若是数字,则长度+1
}
else {
if (count > max) {//倘若当前数字串的长度比最长字符串长,则互换
max = count;
first = i - max;//更改首位置
}
count = 0;//重新赋值为0
}
}
for (int i = first;i < first + max;i++) {
std::cout << a[i];//输出最长数字串
}
return 0;
}