
题目
解决代码及点评
/* 在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付 给其中一个函数参数 outputstr 所指内存。例如: "abcd12345ed125ss123456789"的首地址传给 intputstr 后,函数将返回 9,outputstr 所指的值为 123456789 */ #include <iostream> using namespace std; int FindMaxLen(char *pszBuf, char *pszOutPut) { int nMaxLen = 0; // 保存最长长度 int nTmpLen = 0; // 保存目前累计长度 int nTmpPos; // 保存目前累计长度时的位置 int nMaxPos; // 保存最长长度时位置 int i, j; if (pszBuf == NULL) { return 0; } // 遍历整个字符串 for (i = 0; i < strlen(pszBuf); i++) { nTmpLen = 0; // 如果遇到数字 if (pszBuf[i] >= '0' && pszBuf[i] <= '9') { nTmpPos = i; // 记录临时位置 nTmpLen++; // 累加临时长度 i++; while(pszBuf[i] >= '0' && pszBuf[i] <= '9' && i < strlen(pszBuf)) { // 如果符合条件,则临时长度累加 nTmpLen++; // 判断下一个 i++; } // 如果累加的临时长度大于曾经的最大长度,那么要置换最大长度和最大位置 if(nTmpLen > nMaxLen) { nMaxLen = nTmpLen; nMaxPos = nTmpPos; } } } // 将最大数字字符串保存到pszOutPut for (i = nMaxPos, j = 0; i < nMaxPos + nMaxLen; i++) { pszOutPut[j++] = pszBuf[i]; } return nMaxLen; } // 测试主函数 int main() { char szBuf1[] = "abcd12345ed125ss123456789"; char szBufOut[100] = {0}; int nLen = FindMaxLen(szBuf1, szBufOut); cout<<nLen<<endl<<szBufOut<<endl; system("pause"); return 0; }
代码下载及其运行
代码下载地址:http://download.csdn.net/detail/yincheng01/6704519
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行
程序运行结果