字符串截取算法

获取某字符串中从某字符开始至某字符结束中间的字符串数:

 1 unsigned int get_specified_string_by_chara( char *str, char start, char over, char *substr )
 2 {
 3     char *p1, *p2;
 4     unsigned int len = 0;
 5 
 6     p1 = strchr( str, start );
 7     p2 = strchr( p1 + 1, over );
 8     *substr = 0;
 9 
10     if ( p1 != NULL && p2 != NULL && p2 > p1 + 1 )
11     {
12         while ( ++p1 < p2 )
13         {
14             *substr++ = *p1;
15             len++;
16         }
17         *substr = 0;
18     }
19     return len;
20 }

获取某字符串从出现第N个逗号开始的所有字符数:

 1 unsigned int get_specified_string_by_comma( unsigned char CNT_Comma,char *str,char *substr )
 2 {
 3     char *p=str;
 4     unsigned int len;
 5     
 6     *substr = 0;
 7     if( CNT_Comma )
 8     {
 9         while( isprint(*p) && CNT_Comma )
10         {
11             if( *p++ == ',' ) CNT_Comma--;
12         }
13         if( CNT_Comma ) return 0;
14     }
15     
16     len=0;
17     while( isprint(*p) && *p != ',' )
18     {
19         *substr++ = *p++;
20         len++;
21     }
22     *substr = 0;
23     return len;
24 }

举例说明:

 1 const char* string="+QLTS: \"2019/01/13,03:40:48+32,0\"";
 2 char *pstr, *pstr2;
 3 char *p1, *p2;
 4 u16 temp;
 5 
 6 void main(void)
 7 {
 8   //p1=“TS: \"2019/01/13,03:40:48+32,0\"”
 9   p1=strstr(string,"TS: ");           //比较字符串string是否存在固定字符串,并将p1指针指向该字符串出现第一个字符及后面所有字符
10   if(p1!=NULL)
11   {
12     //temp=4,pstr="2019"
13     temp=get_specified_string_by_chara(p1,'"','/',pstr);//获取从出现第一个字符开始,至第二个字符截止的字符串个数,并将该字符串存放在pstr中
14     if(temp!=0)
15     {
16       //temp=2019
17       temp = atoi(pstr);        //将字符转整形数据给temp
18       if(temp==2019)
19       {
20         //temp=11,pstr="03:40:48+32"
21         temp=get_specified_string_by_comma( 1, p1, pstr );//获取从第一个逗号开始,至第二个逗号截止的字符串个数,并该段字符串存放在pstr中
22         if(temp > 15)
23         {
24           temp=0;
25         }
26       }
27     }
28   }
29   for(;;)
30   {
31     
32   }
33 }

 

posted on 2021-01-20 21:25  Milo_lu  阅读(267)  评论(0编辑  收藏  举报

导航