IT company 100 question-25-find the longest digit string in the string

Source: Internet
Author: User
Problem description:Implement a function to find the longest consecutive numeric string in the string. For example, input "12345cbf3456" and output "12345 ″. Function prototype: void conti_num_max (const char * SRC, char * DEST );

DeST saves the longest numeric string and returns void.

Analysis:Traverse the string and record the start position and length.

Code implementation:

 

 1 // 25.cc 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5  6 void conti_num_max(const char* src, char* dest) { 7     if (!src) { 8         *dest = ‘\0‘; 9         return;10     }11 12     size_t len = 0;13     size_t max_len = 0;14     const char* p = src;15     const char* p_start = NULL;16     while (*p != ‘\0‘) {17         if (*p >= ‘0‘ && *p <= ‘9‘)18             len++;19         else {20             if (len > max_len) {21                 max_len = len;22                 p_start = p - len;23             }24             len = 0;25         }26         p++;27     }28     strncpy(dest, p_start, max_len);29 }30 31 int main() {32     string s;33     cout << "input a str contain num:" << endl;34     getline(cin, s);35 36     char* dest = new char[s.size() + 1];37     conti_num_max(s.c_str(), dest);38     cout << dest << endl;39     return 0;40 }

 

Output:

$ ./a.exeinput a str contain num:123dfasdf123123asdfasdf33333333333333asdfsdf221asdf232333333333333333

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.