#002#人人筆試題 截取html字串

來源:互聯網
上載者:User

標籤:style   blog   http   color   get   width   

C實現

截取html

設定是html字串裡只有<p>標籤,且閉合

輸入:"abc<p class=‘c1‘>defg</p>hijk<p style=‘width=100px;‘>lmn</p>"

截取3個字元

輸出:abc

截取4個字元

輸出abc<p class=‘c1‘>d</p>

 1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 char * htmlSource="abc<p class=‘c1‘>defg</p>hijk<p style=‘width=100px;‘>lmn</p>"; 5 char * GetSubString(char* Source,int length) 6 { 7     int htmlLength=0; 8     for(int i=0;i<strlen(Source);i++) 9     {10         if(Source[i]==‘<‘)11         {12             while(Source[i]!=‘>‘)13                 i++;14         }15         else16             htmlLength++;17     }18     if(length>htmlLength)19     {20         printf("截取長度過長\n");21         return NULL;22     }23     else24     {25         char* target=(char *)malloc(sizeof(char)*(strlen(Source)+1));26         int sum1=0;27         int sum2=0;   28         int flag=0;29         for(int i=0;i<length;i++)30         {31             if(Source[sum2]==‘<‘)32             {33                 if(Source[sum2+1]==‘p‘)34                     flag=1;35                 else if(Source[sum2+1]==‘/‘)36                     flag=0;37                 do38                 {39                     target[sum1++]=Source[sum2++];40                 }41                 while(Source[sum2]!=‘>‘);42                 target[sum1++]=Source[sum2++];43                 target[sum1++]=Source[sum2++];44             }45             else46             {47                 target[sum1++]=Source[sum2++];48             }49         }50         if(flag==1)51         {52             target[sum1++]=‘<‘;53             target[sum1++]=‘/‘;54             target[sum1++]=‘p‘;55             target[sum1++]=‘>‘;56             flag=0;57         }58         target[sum1]=‘\0‘;59         return target;60     }61 }62 void main()63 {64     int length=0;65     while(length!=-1)66     {67         printf("輸入截取長度\n");68         scanf("%d",&length);69         char * target=GetSubString(htmlSource,length);70         printf("%s\n",target);71         free(target);72     }73 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.