- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Explanation:
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,
Example
#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; }
Output
The longest length number in string is 34124
- Related Articles
- Program to find length of longest repeating substring in a string in Python
- Find length of longest subsequence of one string which is substring of another string in C++
- Length of longest string chain in JavaScript
- Find the Length of the Longest possible palindrome string JavaScript
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence in C++
- Program to find length of longest common substring in C++
- Program to find length of longest valid parenthesis from given string in Python
- Longest String Chain in C++
- Longest Happy String in C++
- Find number of magical pairs of string of length L in C++.
- How to get the length of longest string in a PHP array
- Finding the length of longest vowel substring in a string using JavaScript
- Length of Longest Fibonacci Subsequence in C++
- Find length of the longest consecutive path from a given starting characters in C++

Advertisements