读入一个字符串str,输出字符串str中的连续最长的数字串

读入一个字符串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 }
原文地址:https://www.cnblogs.com/Mr-Wenyan/p/8676212.html