讀入一個字符串str,輸出字符串str中的連續最長的數字串
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 int main(int argc,char *argv[]) 5 { 6 //思路:判斷當前位置是數字還是非數字,如果是數字,再判斷當前位置的前一位是數字還是非數字,如果是非數字,則將當前位置存入beg並開始計算長度len。最后判斷哪個位置的數字的長度最大 7 //str:輸入的字符串 8 //beg:數字串的其實位置 len:數字串的長度 9 //maxbeg:最長的數字串的起始位置 maxlen:最長數字串的長度 10 char *str; 11 str=(char *)malloc(256); 12 int cout=scanf("%s",str); 13 int i,beg=500,len=0; 14 int maxbeg=0,maxlen=0; 15 for(i=0;i<strlen(str);i++) 16 { 17 if((*(str+i)>='0')&&(*(str+i)<='9')) 18 { 19 if(i==0) 20 { 21 beg=i;len=1; 22 }else{ 23 if((*(str+i-1)<'0')||(*(str+i-1)>'9')) 24 { 25 if(maxlen<len) 26 { 27 maxlen=len; 28 maxbeg=beg; 29 } 30 beg=i; 31 len=1; 32 }else{ 33 len++; 34 } 35 } 36 } 37 38 } 39 if(maxlen<len) 40 { 41 maxlen=len;maxbeg=beg; 42 } 43 int j=0; 44 while(j<maxlen){ 45 printf("%c",*(str+maxbeg+j)); 46 j++; 47 } 48 49 return 0; 50 }