求一个字符串中的最大长度的数字

本文介绍了一个使用C++编写的程序,该程序能够找出给定字符串中最长的连续数字子串,并返回其长度。通过逐字符扫描并检查是否为数字来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
using namespace std;
int GetMaxLenNumber(char *inputStr,int len)
{
    //开始处理的位置
    int startPos = 0;
    //当前处理的字符长度
    int tempCharCount = 0;
    //数字的最长长度
    int maxLen = 0;

    int pos = 0;
    while (startPos < len)
    {
            //循环中的临时最大长度
            int tempMax = 0;
            while (tempCharCount + startPos < len)
            {
                //开始处理的字符
                char c = inputStr[tempCharCount + startPos];
                if (isdigit(c))
                {
                    //如果是数字
                    tempMax++;
                    if (tempMax > maxLen)
                    {
                        maxLen = tempMax;
                        pos = startPos;
                    }
                }
                else
                {
                    //不是数字
                    tempMax = 0;
                    startPos++;
                    break;
                }
                tempCharCount++;
            }
            if (startPos + tempCharCount == len)
            {
                break;
            }
            tempCharCount = 0;
    }

    return maxLen;
}
int main()
{
    char a[]="654359006 uestc 18224001830 get the longest digit string!";
    puts(a);
    cout<<"GetMaxLenNumber="<<GetMaxLenNumber(a,sizeof(a)/sizeof(a[0]))<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值