Find longest length number in a string in C++

In this problem, we are given a string str consisting of character and alphabets only. Our task is to find the longest length number in a string. 

Problem Description: we need to find the length of the number i.e. consecutive numerical characters in the string.

Let’s take an example to understand the problem, 

Input: str = “code001tutorials34124point”

Output: 34124


Numbers in the string are

001 - size 3

34124 - size 5

Solution Approach

A simple solution to the problem is by traversing the sting and finding the number’s length and its starting index. We will store the starting position and count of characters in the string for each number in the string. And at the end, return the number.

Program to illustrate the working of our solution,


Live Demo

#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])) {
      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