分享

算法9(在字符串中找出连续最长的数字串,并把这个串的长度返回)

 白雪~~~ 2012-03-10

http://blog.csdn.net/yuucyf/article/details/6676568

题目:

写一个函数,它的原形是int continumax(char *outputstr,char *intputstr)
功能:
在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr 所指内存。
例如:"abcd12345ed125ss123456789"的首地址传给intputstr 后,函数将返回9,outputstr 所指的值为123456789

思路一:

这道题目比较简单,遍历一遍就可以,遍历的过程中不断把数字串的最大长度和位置保存下来就可以了.

代码如下:

  1. /*==============================
  2. Copyright by yuucyf. 2011.08.10
  3. ===============================*/
  4. #include "stdafx.h"
  5. #include <assert.h>
  6. #include <iostream>
  7. using namespace std;
  8. typedef struct tagPosInfo
  9. {
  10. int i32Pos;
  11. int i32Len;
  12. tagPosInfo()
  13. {
  14. i32Pos = -1;
  15. i32Len = 0;
  16. }
  17. }S_PosInfo;
  18. int continumax(char *outputstr,char *intputstr)
  19. {
  20. assert(outputstr);
  21. assert(intputstr);
  22. S_PosInfo sMaxPosInfo, sTempPosInfo;
  23. int i32Lenght = _tcslen(outputstr);
  24. for (int i32I = 0; i32I < i32Lenght; i32I++)
  25. {
  26. if (outputstr[i32I] >= '0' && outputstr[i32I] <= '9')
  27. {
  28. if (sTempPosInfo.i32Pos == -1)
  29. sTempPosInfo.i32Pos = i32I;
  30. sTempPosInfo.i32Len++;
  31. }
  32. else
  33. {
  34. if (sTempPosInfo.i32Len > sMaxPosInfo.i32Len)
  35. {
  36. sMaxPosInfo = sTempPosInfo;
  37. }
  38. sTempPosInfo.i32Len = 0;
  39. sTempPosInfo.i32Pos = -1;
  40. }
  41. }
  42. if (sTempPosInfo.i32Len > sMaxPosInfo.i32Len)
  43. {
  44. sMaxPosInfo = sTempPosInfo;
  45. }
  46. if (sMaxPosInfo.i32Len <= 0)
  47. {
  48. return 0;
  49. }
  50. else
  51. {
  52. strncpy_s(intputstr, sMaxPosInfo.i32Len + 1, outputstr+sMaxPosInfo.i32Pos, sMaxPosInfo.i32Len);
  53. return sMaxPosInfo.i32Len;
  54. }
  55. }
  56. int _tmain(int argc, _TCHAR* argv[])
  57. {
  58. char aszSrcStr[] = "abcd12345ed125ss123456789";
  59. char aszDestStr[0x20] = {0};
  60. cout << "输入字串为:" << aszSrcStr << endl;
  61. int i32NumStrLen = continumax(aszSrcStr, aszDestStr);
  62. cout << "输出字串为:" << aszDestStr << " 长度为:" << i32NumStrLen;
  63. return 0;
  64. }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多