(HW OJ)在字符串中找出连续最长的数字串,并返回该数字串的长度

/* 功能:在字符串中找出连续最长的数字串,并把这个串的长度返回
函数原型:
   unsigned int Continumax(char** pOutputstr,  char* intputstr)
输入参数:
   char* intputstr  输入字符串
输出参数:
   char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串
   pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放

返回值:
  连续最长的数字串的长度

 */

unsigned int Continumax(char** pOutputstr,  char* intputstr)
{
    int isDataFlag = 0;  //字符串中是否有数字
    int i = 0, maxLength = 0;
    int beginPos = 0;
    int currLength = 0,currIndex = 0;
 
    for (i = 0; intputstr[i] != '\0'; i++)
    {
        if (intputstr[i] >= '0' && intputstr[i] <= '9')
        {
            currLength = 0;
            isDataFlag = 1;
            currIndex = i;
            while (intputstr[i] != '\0' && (intputstr[i] >= '0' && intputstr[i] <= '9'))
            {
                i++;
                currLength++;
            }
 
            if (currLength >= maxLength)
            {
                maxLength = currLength;
                beginPos = currIndex;
            }
        }
    }
 
    
    if (isDataFlag == 0)/* 说明字符串中没有数字字符 */
    {
        *pOutputstr = "";
    }
    else
    {
        (*pOutputstr) = (char*)malloc(maxLength + 1);
        memset((*pOutputstr), 0, maxLength + 1);
 
        strncpy_s(*pOutputstr, maxLength + 1, intputstr + beginPos, maxLength);
        (*pOutputstr)[maxLength] = '\0';
    }
 
    return maxLength;
}

猜你喜欢

转载自blog.csdn.net/yuhoujiangnan2011/article/details/82558100