在C++中查找字符串中最长数字长度
在这个问题中,我们得到一个仅包含字符和字母的字符串str。我们的任务是查找字符串中最长数字长度。
问题描述:我们需要找到数字的长度,即字符串中连续数字字符的长度。
让我们举个例子来理解这个问题:
输入:str = “code001tutorials34124point”
输出:34124
解释:
字符串中的数字是
001 - 长度为3
34124 - 长度为5
解决方案
解决这个问题的一个简单方法是遍历字符串并找到数字的长度及其起始索引。我们将为字符串中的每个数字存储其起始位置和字符计数。最后,返回该数字。
程序说明了解决方案的工作原理:
示例
#include <iostream>
using namespace std;
string findLongestNumber(string str, int l) {
int count = 0, max = 0, maxLenPos = -1, currPos, currLen, maxLen = 0;
for (int i = 0; i < l; i++) {
currPos = maxLenPos;
currLen = maxLen;
count = 0;
maxLen = 0;
if (isdigit(str[i]))
maxLenPos = i;
while (isdigit(str[i])) {
count++;
i++;
maxLen++;
}
if (count > max) {
max = count;
}
else {
maxLenPos = currPos;
maxLen = currLen;
}
}
return (str.substr(maxLenPos, maxLen));
}
int main() {
string str = "code001tutorials34124point";
int l = str.length();
cout<<"The longest length number in string is "<<findLongestNumber(str, l);
return 0;
}输出
The longest length number in string is 34124
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP