在字符串中找出连续最长的数字串, 例如:abcd12345ed125ss123456789, 输出123456789。
思路:利用一个数组记录各个数字字串的长度。
代码如下:
1 void LongestSubNumberString(const char *Str) 2 { 3 assert (Str != NULL); 4 5 int nLength = strlen (Str); 6 7 if (0 == nLength) 8 { 9 printf ("空字符串!\n"); 10 return; 11 } 12 13 int *MaxLen = NULL; 14 15 if (NULL == (MaxLen = (int *)malloc (nLength * sizeof (int)))) 16 { 17 printf ("Fail to malloc space to MaxLen.\n"); 18 return; 19 } 20 21 const char *pCh = Str; 22 int i = 0; 23 24 if ((*pCh >= '0') && (*pCh <= '9')) 25 { 26 MaxLen[i] = 1; 27 ++pCh; 28 ++i; 29 } 30 else 31 { 32 MaxLen[i] = 0; 33 ++pCh; 34 ++i; 35 } 36 37 while (*pCh != '\0') 38 { 39 if ((*pCh >= '0') && (*pCh <= '9')) 40 { 41 MaxLen[i] = MaxLen[i-1] + 1; 42 ++pCh; 43 ++i; 44 } 45 else 46 { 47 MaxLen[i] = 0; 48 ++pCh; 49 ++i; 50 } 51 } 52 53 int nMax = 0; 54 int j; 55 56 for (i = 0; i < nLength; ++i) 57 { 58 if (MaxLen[i] > nMax) 59 { 60 nMax = MaxLen[i]; 61 j = i; 62 } 63 } 64 65 if (0 == nMax) 66 { 67 printf ("这个字符串不包含数字字串.\n"); 68 return; 69 } 70 71 printf ("最长的数字字串是:\n"); 72 pCh = Str + j - nMax + 1; 73 74 while (nMax > 0) 75 { 76 printf ("%c", *pCh); 77 ++pCh; 78 --nMax; 79 } 80 81 printf ("\n"); 82 }
一些测试结果: