華爲歷年機試題型總結系列(八)

20.字母和數字組成字符串,輸出最長數字串,並返回字符串的長度值

輸入:abc123ss45 輸出:123,當有多個長度相同數字字符串時,輸出最後一個,輸入:aa12345bc44567 輸出:44567

#include<sdio.h>
#include<string.h>

unsigned int ContinueMax(char *pInputStr, char *pOutputStr)
{
     int i,j=0,StrLength,max_numberLength=0,max_numberLength_index=0,count_numberStr_section=-1,k=0;
     int numberStr_length[10]={0};
    
     StrLength=strlen(pInputStr);
     for(i=0;StrLength;)
     {
          if('0'<=pInputStr[i]&&pInputStr[i]<='9')   //如果是數字
           {
                   ++numberStr_length[j]; //對應數字串段數組計數+1
                    if(pInputStr[i+1]<'0'||pInputStr[i+1]>'9') //數字與字母后分界線
                           ++j;
                    ++i;
           }else    //非數字
                   ++i;
     }

     for(i=0;i<j;++i)
         max_numberLength=(max_numberLength>numberStr_length[i])?max_numberLength:numberStr_length[i];    //找出最長數字串的長度

      for(i=0;i<j;++i)
      {
          if(max_numberLength==numberStr_length[i])
              max_numberLength_index=i;  //找出在數組中最長數字串的下標
      }

      for(i=1;i<=StrLength;++i)
      {
           if((pInputStr[i-1]<'0'||pInputStr[i-1]>'9')&&(pInputStr[i]>='0'&&pInputStr[i]<='9'))   //如果是數字與字母的前分界線
            ++count_numberStr_section;
           
          if((pInputStr[i]>='0'&&pInputStr[i]<='9')&&count_numberStr_section=max_numberLength_index) //如果匹配到最長數字字符串
             pOutputStr[k++]=pInputStr[i];
      }

      pOutputStr[k]='\0';
}

int main(void)
{
    char pInputStr[50],pOutputStr[50];
    printf("Input the string:\n");
    gets(pInputStr);

    ContinueMax(pInputStr,pOutputStr);
    puts(pInputStr);
   
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章