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