没有太明白你的需求,如果只是从你给出的示例来看估计是做时间方面的合并处理。那么这里给出的思路是,将时间转化后进行排序,然后按照小时相同进行合并,因为合并之后估计还有可以合并的,所以这里要做while循环,直到不能合并处理完毕,下面给一些示例代码,仅供参考:
#include
#include
#include
#define max_time 8
#define buf_len 8
bool equal( char* str1, char* str2 )
{
char *p1 = str1;
char *p2 = str2;
bool bEqual = false;
while( *p1!=':' && *p2!=':' )
{
if( !(bEqual = *p1++ == *p2++) ) break;
}
return bEqual;
}
bool mergeEqualStr( char* str1,char* str2,char* buff )
{
char *p1 = str1;
char *p2 = str2;
char *b = buff;
while( (*b++=*p1++) !=':' );
while( *p2++ != ':' );
int num1 = atoi( p1 );
int num2 = atoi( p2 );
sprintf_s( b,4,"%d",num1+num2);
return true;
}
int timeToi( const char* t )
{
if( *t=='\0' ) return 0;
char _buffer[8]={0};
memcpy( _buffer,t,8 );
char* _h = _buffer;
char* _m = _buffer;
while( *_m++ !=':');
*(_m-1)='\0';
return atoi( _h )*60+atoi( _m );
}
void timeToa( int _t,char* _time )
{
int _h = _t/60 ;
int _m = _t%60 ;
_itoa_s( _h,_time,4,10 );
char *p = _time;
while( *p++ !='\0');
*(p-1) = ':';
_itoa_s( _m,p,4,10 );
}
void timeAtoi( char timeStr[][32],int timeNumBuf[] )
{
for( int i=0;i{
timeNumBuf[i]=timeToi( timeStr[i] );
}
}
void timeItoa(int timeNumBuf[],char timeStr[][32])
{
for( int i=0;i{
if( timeNumBuf[i]!=0 )
timeToa( timeNumBuf[i],&timeStr[i][0] );
}
}
bool merge( char timeStr[max_time][32],char timeBuf[max_time][32] )
{
int index = 0;
bool bMerge=false;
for( int i=1;i{
if( equal( timeStr[i-1],timeStr[i] ))
{
mergeEqualStr( timeStr[i-1],timeStr[i],timeBuf[index++]);
++i;
bMerge = true;
}
else
{
memcpy(timeBuf[index++], timeStr[i-1], buf_len );
}
}
return bMerge;
}
void TestMerge()
{
char timeStr[max_time][32]={"1:20","2:20","3:20","3:50","4:20","5:20"};
printf("merge list:");
for( int i=1;i{
if( timeStr[i] =="" )break;
printf("%s,",timeStr[i]);
}
char timeBuf[max_time][32]={0};
int timeNumBuf[max_time]={};
while(merge( timeStr,timeBuf ))
{
timeAtoi( timeBuf,timeNumBuf );
memset( timeStr,0,32*max_time);
timeItoa( timeNumBuf,timeStr );
memset( timeBuf,0,32*max_time);
}
printf("\nmerged list:");
for( int i=1;i{
printf("%s,",timeBuf[i]);
}
}
int main(int argc, char* argv[])
{
TestMerge();
return 0;
}
以上代码不够严谨也不规范,仅供参考。运行结果:
最后再给自己打一个小广告 :), http://www.iu8s.com/
合并的规则是什么?